C++随机数累加程序报标识符未定义、缺少分号错误如何解决
错误原因及修复方案
编译错误对应问题
- 第14行
Expected a ;:int sum = 0末尾遗漏分号,该错误会导致后续定义的char response被编译器识别为sum变量定义的一部分,直接触发第16行identifier response is undefined报错 - 第27行
Expected a ;:判断sum超过50的分支里,cout语句末尾和break语句末尾均遗漏分号
其他隐藏语法/逻辑错误
- 输入运算符使用错误:
cin的输入运算符为>>,代码中误写为<< - 判断逻辑误用赋值运算符:
while (response = 'y')、if (response = 'n')中使用赋值符=而非相等判断符==,会导致逻辑判断完全失效 rng函数设计错误:当前rng为void返回类型,仅负责打印随机数,无法返回数值用于累加,需要改为返回int类型,且函数内不要直接打印结果- cout输出语法错误:输出语句中多余的
+符号属于语法错误,直接用<<拼接输出内容即可 - 累加逻辑缺失:当前代码没有将随机数累加到sum的逻辑,无法实现求和功能
- 随机数种子未初始化:直接调用
rand()会导致每次运行程序生成的随机数序列完全相同,需要在程序开头用srand(time(NULL))初始化随机种子
修复后完整代码
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int rng(){ return (rand() % 12) + 1; } int main() { srand(time(NULL)); // 初始化随机数种子 int sum = 0; char response; cout << "Would you like to add a number? y or n: "; cin >> response; while (response == 'y') { int num = rng(); sum += num; cout << "Okay then, the current sum is " << sum << ", the new added number is " << num << endl; if (sum >= 50) { cout << "Alright the sum has reached 50 that seems like enough" << endl; break; } cout << "Would you like to add a number? y or n: "; cin >> response; } if (response == 'n') { cout << "Okay thanks, have a good one" << endl; } return 0; }
内容的提问来源于stack exchange,提问作者Wargrave
相关产品推荐
相关产品推荐

