c# - 使用 for 循环创建平均测试分数
问题描述
我正在尝试使用 for 循环计算出最多 4 个测试分数的测试分数。似乎我要超过 4 而不是停下来,并且不确定我做错了什么,因为它没有显示我的平均值。请指教:
Console.WriteLine("Please enter your first test score");
//variables
double testScore = double.Parse(Console.ReadLine());
double average = 0;
for (int count = 0; count <= 4; count++) // Start the count from 0-4
{
//get the total
average = average + testScore;
Console.WriteLine("Please enter your other test score");
testScore = double.Parse(Console.ReadLine());
//Calculate and display
Console.WriteLine("The average of your test score is :", average / count);
}
}
解决方案
如果我理解正确,你需要一个小于号不小于或等于
for (int count = 0; count < 4; count++)
原因是你从 0 开始,即循环迭代0,1,2,3,4
或者(并且因为)您使用除法计数,您实际上应该从 1 开始
for (int count = 1; count <= 4; count++)
最后,您应该始终检查用户输入是否有肮脏的小手指
while(!double.TryParse(Console.ReadLine(),out testScore))
Console.WriteLine("You had one job!);
public static bool TryParse (string s, out double result);
将数字的字符串表示形式转换为其等效的双精度浮点数。返回值指示转换是成功还是失败。
完整示例
double sum = 0;
for (int count = 0; count <= 4; count++) // Start the count from 0-4
{
Console.WriteLine("Please enter your other test score");
while(!double.TryParse(Console.ReadLine(),out testScore))
Console.WriteLine("You had one job!);
sum += testScore;
//Calculate and display
Console.WriteLine($"The average of your test score is : {(sum / (double)count):N2}");
}
推荐阅读
- javascript - 如何在 TypeORM 模型中保持一对多关系的“多”方唯一?
- bash - 从另一个分支创建分支时对“父”Git 分支的 Bash 引用
- c++ - Qt 的交互式命令行界面
- geolocation - 如何标准化用户插入的城市名称
- python - TensorFlow 输入中的形状未对齐
- kotlin - 当我尝试运行 Kotiln 文件时,Intellij 中的运行按钮被禁用。为什么?
- django - 使用 DRF 时出现 Django BuiltinSignatureError
- javascript - 如何使用 useReducer 钩子和 setInterval 在 React 中创建秒表?
- assembly - 为什么我的数据段与我的代码段冲突?
- c++ - 数组必须用大括号括起来的初始化程序 c++ 初始化