所以我做了一个while
循环,要达到12个等级。计数器从0开始。在Main()
方法中,我调用函数gradeFunction()
,但执行完该函数后,计数器没有任何变化。
Program p = new Program();
string name = Console.ReadLine();
int gradesPassed = 12;
int currentGrade = 0;
double totalSumOfGrades = 0;
while(currentGrade <= gradesPassed)
{
double finalGrade = double.Parse(Console.ReadLine());
p.gradeFunction(finalGrade, totalSumOfGrades, currentGrade);
}
被调用函数:
public void gradeFunction(double finalGrade, double totalSumOfGrades, int currentGrade)
{
if(finalGrade >= 4.00)
{
totalSumOfGrades += finalGrade;
currentGrade++;
}
}
答案 0 :(得分:2)
代码
Console.ReadLine();
double totalSumOfGrades = 0;
for(var currentGrade = 0; currentGrade <= 12; currentGrade++)
{
var finalGrade = double.Parse(Console.ReadLine());
if (finalGrade >= 4.00)
{
totalSumOfGrades += finalGrade;
}
}
将更简单,更直接。
答案 1 :(得分:1)
就像@杰里米(Jeremy)所说,请尝试以下操作:
Program p = new Program();
string name = Console.ReadLine();
int gradesPassed = 12;
int currentGrade = 0;
double totalSumOfGrades = 0;
while (currentGrade <= gradesPassed)
{
double finalGrade = double.Parse(Console.ReadLine());
gradeFunction(finalGrade, ref totalSumOfGrades, ref currentGrade);
}
public static void gradeFunction(double finalGrade, ref double totalSumOfGrades, ref int currentGrade)
{
if (finalGrade >= 4.00)
{
totalSumOfGrades += finalGrade;
currentGrade++;
}
}
我在调用和声明上都添加了currentGrade
和totalSumOfGrades
的ref关键字,以便正确更新变量,我认为这是使代码正常工作的最无影响的方法