[英]How to use `Console.WriteLine` properly
I want to show the full equation 1 + 2 = 3
.我想显示完整的方程
1 + 2 = 3
。
My attempt so far :到目前为止我的尝试:
double x = 1, y = 2;
double add = x + y ;
Console.WriteLine(add);
Console.WriteLine("Press any key to continue");
Console.ReadKey();
Though, this gives me only 3
as output!虽然,这给我只有
3
作为输出! any suggestions有什么建议
Console.WriteLine(x+" + "+y+" = "+add);
Try this:尝试这个:
Console.WriteLine("{0} + {1} = {2}", x, y, add)
chouaib's answer is also valid, if you favor string concatenation over substitution.如果您喜欢字符串连接而不是替换,chouaib 的回答也是有效的。
Try this one试试这个
double x = 1, y = 2;
string add = String.Format("{0} + {1} = {2}", x, y, x + y);
Console.WriteLine(add);
Console.WriteLine("Press any key to continue");
Console.ReadKey();
This looks a lot like you're asking us to do a homework question, so I won't post the exact code (which is left as an exercise for you), but check out the String.Format method.这看起来很像您要求我们做一个家庭作业问题,所以我不会发布确切的代码(留给您作为练习),但请查看String.Format方法。 Use it to build a string containing the equation with placeholders replaced with the variables, and then pass that string to Console.WriteLine
使用它来构建一个包含等式的字符串,其中占位符替换为变量,然后将该字符串传递给 Console.WriteLine
The problem with your code is that you only wrote Console.WriteLine(add)
which instructs the program to display only the "add" value.您的代码的问题在于您只编写了
Console.WriteLine(add)
,它指示程序仅显示“添加”值。
Try this code:试试这个代码:
double x = 1, y = 2;
double add = x + y ;
Console.WriteLine("{0} + {1} = {2}", x, y, add.ToString());
Console.WriteLine("Press any key to continue");
Console.ReadKey();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.