我有这段代码来阅读用户输入。
Console.WriteLine(userName + " How many hours did you work in the last two weeks");
string hrsWrkd = Console.ReadLine();
Console.WriteLine("You worked:" + hrsWrkd + "hrs");
Console.WriteLine(userName + "Your Gross paycheck is ");
string grossPay = (hourlyRate*hrsWrkd);
Console.WriteLine();
我想将这些值相乘:
string grossPay = (hourlyRate*hrsWrkd);
我是编程新手,需要帮助才能理解错误,以及如何正确完成。
答案 0 :(得分:3)
解析字符串以便获得数字,然后您可以在计算中使用它。结果也是一个数字,所以如果你想把它作为一个字符串,你需要转换它。例如:
int hours = Int32.Parse(hrsWrkd);
string grossPay = (hourlyRate * hours).ToString();
答案 1 :(得分:0)
使用double而不是string。字符串不能做数学。
double grossPay = hourlyRate * hrsWrkd;
答案 2 :(得分:0)
您的代码不包含变量所属的类型。假设它们是double
,decimal
或float
,那么您的代码就可以运行。
例如
double hourlyRate = 20.25, hrsWrkd = 10.5;
double grossPay = (hourlyRate*hrsWrkd);
Console.WriteLine(grossPay);
答案 3 :(得分:0)
你可以试试这样的......
grossPay = Convert.ToString((hourlyRate*hrsWrkd));
这将执行计算,然后将答案转换为字符串,并将值存储到grossPay。
确保将hourlyRate和hrsWrked声明为双变量。
答案 4 :(得分:0)
当您从控制台应用程序中读取输入时,请使用
Console.ReadLine();
但是,此方法仅返回类型为String
的值。
类型String
仅用于文本内容。如果您必须处理数字并执行数学运算,则必须使用a type that handle numbers。
如上所述,您可以使用数字类型的Parse
或TryParse
方法将string
转换为数字类型。
double numericValue = double.Parse(Console.ReadLine());
使用上面的示例,您将从控制台读取文本,并使用Double.Parse
method将其转换为double
类型的值。
一旦你拥有了一个数字类型的所有变量,你可以将它们相乘:
double hourlyRate = double.Parse(Console.ReadLine());
double hrsWrkd = double.Parse(Console.ReadLine());
double grossPay = hourlyRate * hrsWrkd;