关于#c++#的问题:代码运行后输出的结果一直是,Right WRONG.GUESS IS LOW


#include
#include
int main()
{
    int magic, guess;
    magic = rand();
    guess = 777;
    if (guess = magic)
        printf("Right");
    else if (guess >= magic)
        printf("Wrong,guess is high");
    else(guess <= magic);
        printf("Wrong,guess is low"); 
}


代码运行后输出的结果一直是,Right WRONG.GUESS IS LOW

  • 你要先设置随机数种子,再调用 rand() 获取随机值
  • 第一个if 修改成==; 最后一个 else 后面是分号
  • 完整修改如下
 
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
    int magic, guess;
    srand((unsigned)time(NULL)); //根据系统时间初始化随机种子
    magic = rand() % 1000; // 0~999 之间的随机数
    printf("%d\n", magic);
    guess = 777;
    if (guess == magic)
        printf("Right");
    else if (guess > magic)
        printf("Wrong,guess is high");
    else 
        printf("Wrong,guess is low"); 
}

if (guess == magic) ,是==,不是=
else(guess <= magic);后面的分号删除掉!