Console.Writeline不会打印所需的结果

时间:2015-01-18 16:06:04

标签: c#

出了什么问题,console.writeline接受一个字符串参数后跟对象-up到18我想 - !

Console.WriteLine( "Grade Report : \n",
"{0} grades was entered, total grade is : {1}\n",
"Class average : {2:F}\n",
"\nA : {3}, \nB : {4}, \nC : {5}, \nD : {6}",
gradeCounter, gradeTotal, ( double ) gradeTotal / gradeCounter,
aCount, bCount, cCount, dCount );

我得到的输出是:

Grade Report :

谢谢!

3 个答案:

答案 0 :(得分:1)

要使用提供的变量格式化字符串,您需要删除逗号:

Console.WriteLine("Grade Report : \n" +
    "{0} grades was entered, total grade is : {1}\n" +
    "Class average : {2:F}\n" +
    "\nA : {3}, \nB : {4}, \nC : {5}, \nD : {6}",
    gradeCounter, gradeTotal, ( double ) gradeTotal / gradeCounter, aCount, bCount, cCount, dCount);

这是方法定义:

public static void WriteLine(string format, params Object[] arg)

所以第一个字符串是你的模板字符串。用逗号分隔的每个参数都被视为一个参数,用于替换该字符串中的占位符。

答案 1 :(得分:1)

试试这个:

Console.WriteLine( 
    String.Format("Grade Report : \n {0} grades was entered, total grade is :{1}\n Class average : {2:F}\n\n A : {3}, \nB : {4}, \nC : {5}, \nD : {6}",
        gradeCounter, gradeTotal, 
        ( double ) gradeTotal / gradeCounter, aCount, bCount, cCount, dCount 
    )
);

String.Format方法用于占位符/值替换,如Console.WriteLine也可以。它的使用是多余的,所以你可以解开这个功能。但不影响输出。

答案 2 :(得分:0)

Console.WriteLine期望参数化字符串作为第一个参数,并且在逗号之后它需要参数。您还可以使用@使用新行格式化字符串。所以你最终会得到以下结论:

Console.WriteLine(@"Grade Report : 
{0} grades was entered, total grade is : {1}
Class average : {2:F}
A : {3}, 
B : {4}, 
C : {5}, 
D : {6}",
1, 2, (double)3 / 4,
5, 6, 7, 8);

输出:

enter image description here