Okay so my program is supposed to take values that the user gives and then performs a calculation with them and then returns them, the problem is that when I try to write a Console.WriteLine to print the values, nothing appears where the variable should and I have no idea what I'm doing wrong
double HumanStrideLength = 0;
double HumanHeight;
double HumanVelocity;
double HumanStrideFrequency = 0;
string Answer;
string AnimalName;
double AnimalLength;
double AnimalStrideLength;
Console.WriteLine("Hello and welcome to Animal Run");
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
Console.WriteLine("Do you know your stride length?");
Answer = Console.ReadLine();
if ((Answer == "Yes") || (Answer == "yes") || (Answer == "y") || (Answer == "Y") || (Answer == "Yeah") || (Answer == "yeah"))
{
Console.WriteLine("Please input your stride length in CM");
try
{
HumanStrideLength = double.Parse(Console.ReadLine());
}
catch(FormatException f)
{
Console.WriteLine(f.Message);
}
}
else
{
Console.WriteLine("What is your height in CM");
HumanHeight = Double.Parse(Console.ReadLine());
HumanStrideLength = HumanHeight * 0.413;
}
Console.WriteLine("test", HumanStrideLength);
So here where it is supposed to print the variable HumanStrideLength it instead prints just the word "test".
答案 0 :(得分:6)
If you call Console.WriteLine()
with multiple arguments, the first argument must be a format string. This means that it has to contain something like {0}
, which is a placeholder that will be replaced by the additional arguments to Console.WriteLine()
. For example, change:
Console.WriteLine("test", HumanStrideLength);
to
Console.WriteLine("test {0}", HumanStrideLength);
And the output you should see if HumanStrideLength
is 12.3
, for example, will be:
test 12.3
or
test 12.3000001
due to floating point inaccuracy.
You can include multiple placeholders like this, with the number inside of each one corresponding to the zero-based index of the parameter that it will be replaced with:
Console.WriteLine("testing {0}, {1}", 2.3, 4.5);
will write "testing 2.3, 4.5" to the console. See documentation on MSDN for more information on this.
If you want to be more concise, you can also just use string interpolation instead of a format string. This feature was introduced in C# 6:
Console.WriteLine($"test {HumanStrideLength}");