我今年开始上大学,学习软件开发类(class)。我刚开始在 C++ 中做循环,并被分配了一些要解决的问题。我已经为第一个问题完成了代码,但部分输出无法正常工作,我无法弄清楚原因。
问题是在一次测试中读入 10 名学生的分数,然后输出获得荣誉分数(超过 70 分)的学生的百分比
这是我的代码
int _tmain(int argc, _TCHAR* argv[])
{
int grade;
int numfirstclass = 0;
int percentfirstclass;
for (int count = 0; count < 10; count++)// For loop to run 10 times to allow 10 grades to be entered
{
cout << "Enter your grade ";
cin >> grade;
if (grade >= 70)
numfirstclass++;
}
cout << "The number of students with a first class honours degree is:" << numfirstclass;
percentfirstclass = (numfirstclass / 10) * 100;
cout << endl << "The Percentage of students that recieved a first class degree is: " << percentfirstclass;
return 0;
}
我的问题是 percentfirstclass 的输出始终为 0,我不知道为什么。
任何解释将不胜感激
我正在使用 visual studio 2013
最佳答案
使用
percentfirstclass = (numfirstclass / 10(double)) * 100;
numfirstclass/10
将始终计算为 0(当 numfirstclass
为 1 时除外),因为它是整数除法,并且 100 与 0 相乘始终为 0。
使用强制转换将使 numfirstclass/10(double)
产生一个带有小数部分的数字,然后将其与 100 相乘。然后,此数字将分配给 percentfirstclass
,并且由于 percentfirstclass
是 int
,小数部分将被截断。
关于C++ For循环初学错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574486/