C# 枚举的令牌错误无效
我为一个简单的程序编写的代码有点问题。我在说“无效令牌”时收到大量错误 程序基本上要求2个整数并求和,但程序需要用另一种方法调用C# 枚举的令牌错误无效,c#,C#,我为一个简单的程序编写的代码有点问题。我在说“无效令牌”时收到大量错误 程序基本上要求2个整数并求和,但程序需要用另一种方法调用 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AustinPDangeloJPA03 { class Add { static void Main(string[] args)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AustinPDangeloJPA03
{
class Add
{
static void Main(string[] args)
{
double num1,
num2,
sum;
Console.Write("Enter the First integer: ");
num1 = int.Parse(Console.ReadLine());
//First Integer entered and storred
Console.Write("Enter the Second integer: ");
num2 = int.Parse(Console.ReadLine());
//Second Integer entered and storred
sum = Display(double a, double b);
//First and second numbers added together
Console.WriteLine(" {0} + {1} = {2} ",num1,num2,sum);
//displays the sum
//Instructs the user to press the Enter key to end the program
Console.WriteLine("Press the Enter key to terminate the program...");
Console.ReadLine();
}//Closes Main Method
static enum Display(a,b)
{
double c = a + b;
return c;
}//closes display method
}//Closes Class Add
}
您的
Display
方法声明不正确
您需要声明一个接受两个数字并返回第三个数字的方法。有关如何声明方法和使用何种类型的更多信息,请参阅教科书和作业 您也没有正确地调用它;方法调用不采用类型。这是不正确的:
static enum Display(a,b)
{
double c = a + b;
return c;
}
用于声明枚举。为了定义方法,您需要一个有效的返回类型(例如int
或double
),并且需要为各个参数提供适当的类型。如果希望它是一个静态方法,您可以选择添加static
,但这取决于它的用途
我怀疑您想使用更像:
double Add(double a, double b)
{
// ...
如果随后更正调用此方法的行:
sum = Display(double a, double b);
这应该可以编译并提供您所期望的内容。虽然它不是错误的来源,但它确实表明对类型的误解:
double num1, num2,sum;
[...]
num1 = int.Parse(Console.ReadLine());
第一行声明了一些double
变量。第二行尝试解析
int
变量
虽然
int
将自动转换为double
,但如果代码与类型的使用一致,则代码会更好。您应该切换到int
类型,或者切换到Double.Parse()
关键字enum
用于创建枚举,例如:
public enum Color { Red, Green, Blue };
必须为Display
方法指定数据类型作为返回类型,并为参数指定数据类型:
static double Display(double a, double b) {
double c = a + b;
return c;
}
此外,调用该方法时不指定数据类型,因此将其更改为:
sum = Display(a, b);
将此行更改为:
double sum = Display(num1, num2);
并将显示方法更改为方法
private static double Display(double a, double b)
{
double c = a + b;
return c;
}
你认为“静态枚举”是什么意思?不管你认为它意味着什么,那不是它的意思。你能解释一下你的想法吗?我非常有兴趣了解人们对代码含义的直觉是如何将他们引入歧途的,这样我们就可以设计出不会让用户陷入这些陷阱的语言。谢谢@埃里克:说得很好。为了回答您的问题,我怀疑他认为
enum
是一种数字类型,或者他随机选择了一个关键字。“我收到了大量错误,比如“无效令牌”-至少显示几个错误,以及它们所指的行号。告诉我们您的代码中某处存在“无效令牌”是对您请求帮助的同一个人的滥用!我知道它的家庭作业,您可能要求以一种非常特殊的方式对代码进行注释——但实际上,如果我看到像Console.WriteLine(…);//写入控制台
,i++;//递增'i'变量
,或//关闭主方法我会刺伤原始作者的眼睛。每行代码后面的注释,特别是自解释行,都是噪音。请代表我诽谤您的讲师。@Slaks:并没有试图提供完整的解决方案-只是提供足够的提示,并说明原因,以使OP出现…详细说明@ReedCopsey about enum。从文档中可以看到:枚举元素的默认底层类型是int。这意味着枚举基本上是int。里德说的也是。因为这是一个QA站点。