【发布时间】:2014-12-21 20:38:06
【问题描述】:
我今年开始上大学,学习的是软件开发课程。我刚刚开始在 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
【问题讨论】:
-
numfirstclass/10始终为 0,因为numfirstclass是int的值 int 计算,请将其更改为double,如果您还是有问题。 -
您强制 C++ 首先评估
numfirstclass/10,对于低于 10 的每个数字(因为它们是整数),这将是0。乘以 100 来得太晚了。删除括号并将100放在开头。 ...或乘以 (100/10)。 -
谢谢大家,我把它改成了双倍,现在可以工作了。对不起菜鸟的错误。我现在明白了