简体   繁体   中英

Trouble with method subtraction c#

I am experiencing some difficulty with method. My code seems to work just fine until I reach my formula for method. I have done something similar I'm not seeing what I'm doing wrong. It is the portion that has 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();

Thank-you for the assistance.

Try this:

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

As MSDN says, 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

And that might not be the value you are expecting.

This should work:

    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(); work similar to string.Format(); when inserting a string;
The 1st parameter after the string will be {0}, second string {1} and so on...

The issue is you are calling Console.Write("\\nYou will work:", YearsToWork); which only writes the string and nothing else, if you wanted to generate a more elaborate message you should use string.Format or the Console.WriteLine . Your code should be something like this:

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();

Notice that I have set all variable names to lowerCamelCase and declared them as needed, also I made a variable (which could as well be a constant) for the 65 constant you were using. All these are best practice recomendations. Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM