方法减法 c# 的问题

Trouble with method subtraction c#

我在使用方法时遇到了一些困难。在我找到我的方法公式之前,我的代码似乎工作得很好。我做了类似的事情我没有看到我做错了什么。这是有 yearsToWork 的部分。

int age;
int yearsToWork;

Console.Write("Enter your name:");
string name = Console.ReadLine();

Console.Write("Enter your age:");
age = Convert.ToInt32(Console.ReadLine());

yearsToWork = 65 - age;
Console.Write("\nYou will work:", yearsToWork);
Console.Write("years before you retire.");
Console.Read();

感谢您的帮助。

试试这个:

Console.Write("\nYou will work: " + YearsToWork.ToString());

正如 MSDN 所说,Console.Write:

Writes the text representation of the specified object to the standard output stream using the specified format information.

https://msdn.microsoft.com/en-us/library/9xdyw6yk(v=vs.110).aspx

这可能不是您期望的值。

这应该有效:

    static void Main(string[] args)
    {
        int age;
        int YearsToWork;

        Console.Write("Enter your name:");
        string name = Console.ReadLine();
        Console.Write("Enter your age:");
        age = Convert.ToInt32(Console.ReadLine());
        YearsToWork = 65 - age;
        Console.WriteLine("You will work: {0} years before you retire", YearsToWork);
        Console.Read();
    }

Console.WriteLine();工作类似于 string.Format();插入字符串时;
字符串后的第一个参数将为 {0},第二个字符串为 {1},依此类推...

问题是您正在调用 Console.Write("\nYou will work:", YearsToWork);,它只写入 string 而没有其他内容,如果您想生成更详细的消息,您应该使用 string.Format or the Console.WriteLine。您的代码应该是这样的:

int maxWorkAge = 65;
Console.Write("Enter your name:");

string name = Console.ReadLine();
Console.Write("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());

int yearsToWork = maxWorkAge - age;

Console.WriteLine();
Console.Write("You will work: {0} years before you retire.", yearsToWork);
Console.Read();

请注意,我已将所有变量名称设置为 lowerCamelCase 并根据需要声明它们,我还为 [=15 创建了一个变量(也可以是常量) =] 你正在使用的常量。所有这些都是最佳实践建议。希望这有帮助