如何在C++代码中统计if条件为真的数量以计算用户得分
解决方法:统计答题得分
要统计用户答对的题目数量并展示总分,只需添加一个得分变量,每次用户答对时递增该变量即可。以下是修改后的完整代码,同时修复了原代码中提示信息的错误:
#include <iostream> using namespace std; int main() { int num[4][4] { {2,5,26,677} , {2,3,7,5041} , {1,2,3,4}, {1,3,5,7} }; int ans[4]; int score = 0; // 初始化得分为0 cout << "hello user.\n"; cout << "write your answer" << endl; cout << "2, 5, 26 , "; cin >> ans[0]; cout << "write your answer\n"; cout << "2, 3, 7, "; cin >> ans[1]; cout << "write your answer\n"; cout << "1, 2, 3, "; cin >> ans[2]; cout << "hello user.\n"; cout << "write your answer" << endl; cout << "1, 3, 5,"; cin >> ans[3]; // 检查第一题 if (ans[0] == num[0][3]) { cout << "your first answer is right\n"; score++; // 答对,得分+1 } else { cout << "your first answer is wrong, the right answer is " << num[0][3] << "\n"; } // 检查第二题 if (ans[1] == num[1][3]) { cout << "your second answer is right\n"; score++; } else { cout << "your second answer is wrong, the right answer is " << num[1][3] << "\n"; } // 检查第三题 if (ans[2] == num[2][3]) { cout << "your third answer is right\n"; score++; } else { cout << "your third answer is wrong, the right answer is " << num[2][3] << "\n"; } // 检查第四题 if (ans[3] == num[3][3]) { cout << "your fourth answer is right\n"; score++; } else { cout << "your fourth answer is wrong, the right answer is " << num[3][3] << "\n"; } // 展示总分 cout << "your score is " << score << endl; }
关键修改点:
- 添加
int score = 0;初始化得分变量。 - 每答对一题执行
score++,实现得分累加。 - 修正原代码中提示信息的错误(比如第一题误显示"second answer")。
- 最后通过
cout输出最终总分。 - 用
num[i][3]替代硬编码的正确答案,提升代码可维护性。
内容的提问来源于stack exchange,提问作者omar benadada
相关产品推荐
相关产品推荐

