我一直在努力编写一个计算年终成绩的C ++程序(Google for Education C ++课程的练习)。该程序有效,除了它不计算你的最终成绩这一事实,相反,它只输出“0”。我搜索了代码,似乎无法找到问题。< / p>
#include <iostream>
using namespace std;
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return 0;
}
}
int assignments() {
int assignment1 = 0;
int assignment2 = 0;
int assignment3 = 0;
int assignment4 = 0;
cout << "Enter the score for the first assignment. ";
check(assignment1);
cout << "Enter the score for the second assignment. ";
check(assignment2);
cout << "Enter the score for the third assignment. ";
check(assignment3);
cout << "Enter the score for the fourth assignment. ";
check(assignment4);
return ((assignment1 + assignment2 + assignment3 + assignment4) / 4 * 0.4);
}
int mid() {
int midterm = 0;
cout << "Enter the score for the midterm. ";
check(midterm);
return (midterm * 0.15);
}
int finalex() {
int finals = 0;
cout << "Enter the score for the final. ";
check(finals);
return (finals * 0.35);
}
int participation() {
int parti = 0;
cout << "Enter the class participation grade. ";
check(parti);
return (parti * 0.1);
}
int main() {
int assign = assignments();
int midt = mid();
int fingra = finalex();
int partigra = participation();
cout << "The final grade is: " << assign + midt + fingra + partigra << endl;
}
(我为每个年级类型设置不同的程序的原因是因为该课程声明您应该尽可能多地创建函数)
答案 0 :(得分:1)
要么将值传递给check()作为引用,要么检查以返回输入值。
更改
int check(int a)
到
int check(int& a)
第二种方法
修改检查到
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return a;
}
}
并使用返回值为变量分配输入。喜欢
int midterm = 0;
cout << "Enter the score for the midterm. ";
midterm=check(midterm);
答案 1 :(得分:0)
您的cin >> a
语句更新了check()
返回后立即消失的局部变量的值。您想要更新实际用于计算成绩的变量的值。只需更改函数check()
即可通过引用传递check(int &a)
或传递指针check(int *a)