You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++简易加法游戏IF分支不执行:为何始终触发ELSE分支?

问题分析与修复方案

嘿,这问题太典型了——变量赋值顺序搞反了,导致你的answer变量存的根本不是你想要的两个随机数的和!

核心错误点

你看这段代码的顺序:

int answer = number[0] + number[1]; // 这里number数组还没赋值!
number[0] = randnum;
number[1] = randnum * randnum - 23;

当你计算answer的时候,number[0]和number[1]都是未初始化的内存值(也就是所谓的“垃圾值”),而不是后面你生成的那两个随机数。等你给数组元素赋值后,answer的值并没有自动更新,所以后面和玩家输入的playeranswer对比时,永远是在拿垃圾值和正确答案比,自然每次都走else分支输出Wrong。

修复后的代码

只需要把计算answer的语句放到给number数组赋值之后就行,另外顺便给你加个随机数种子的初始化(不然每次运行生成的随机数都一样):

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    // 初始化随机数种子,确保每次运行随机数不同
    srand(time(0));
    
    int randnum = rand() % 100;
    int number[2];
    int playeranswer = 0;
    
    // 先给数组赋值
    number[0] = randnum;
    number[1] = randnum * randnum - 23;
    // 再计算正确答案
    int answer = number[0] + number[1];
    
    cout << number[0] << "+" << number[1] << endl;
    cout << "What's your answer to the question?" << endl;
    cin >> playeranswer;
    
    if (playeranswer == answer) {
        cout << "Yep, that's the right answer" << endl;
    } else {
        cout << "Wrong" << endl;
        cout << "The answer is..." << answer << endl; // 这里直接用已经计算好的answer就行
        cout << "Your answer was..." << playeranswer << endl;
    }
    
    return 0;
}

额外优化小提示

  • 修复后else分支里可以直接用已经计算好的answer,不用再重新计算number[0]+number[1],避免重复代码。
  • 记得包含必要的头文件(比如<cstdlib>和<ctime>),不然rand()和srand()可能无法正常工作。

内容的提问来源于stack exchange,提问作者Pazzhy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:42:01