2017-02-06 40 views
0

我遇到了一些方法上的困難。我的代碼似乎工作得很好,直到我達到我的方法公式。我做了類似的事情,我沒有看到我做錯了什麼。這是有幾年工作的部分。方法減法問題c#

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

感謝您的幫助。

+5

問題是什麼? – SLaks

+2

請參閱「Console.Write()'的文檔。參數並不意味着你認爲他們的意思。 – SLaks

回答

1

這應該工作:

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} ...等

+0

是的,它工作,非常感謝你!另外,謝謝你解釋它。對於C#我還是比較新的,現在我明白了一點。 – Shade

0

的問題是,你在呼喚Console.Write("\nYou will work:", YearsToWork);只寫string,沒有別的,如果你想生成一個更詳細的信息,你應該使用string.FormatConsole.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,並宣佈他們需要,我也做了一個變量(這可能也成爲一個常數)爲65你正在使用的常數。所有這些都是最佳做法推薦。希望這可以幫助