我正在尝试制作一个随机数生成器猜测游戏,这将允许用户选择一个范围。挑选范围后,用户将尝试猜测数字,直到他们做对。我是c ++的新手,不明白为什么两个cout输出在屏幕上。我是c ++的新手,无法弄清楚原因。我正在使用visual studio 17。
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <cstdlib>
using namespace std;
int main()
{
int userNum;
char choice;
int numattempts = 0;
int randNumber;
srand(time(0));
cout << "Welcome to the number guessing game\n" << "Please choose what range you want to guess from\n" << " '1' = 0-20\n '2'= 0-50\n '3'= 0-100\n ";
cin >> choice;
if (choice == '1')
{
randNumber = 0 + rand() % 20;
cout << "Enter a number between 0 and 20\n";
cin >> userNum;
cout << randNumber;
do {
if (userNum < randNumber)
{
cout << "Number is Higher\n";
cin >> userNum;
}
else if (userNum > randNumber)
{
cout << "Number is Lower\n";
cin >> userNum;
}
else (userNum == randNumber);
{
cout << "Congrats You got it!\n";
}
} while (userNum != randNumber);
}
答案 0 :(得分:0)
如果在最后一次检查中你错过了另一个,不应该在那里加分号。 尝试调试,你会发现它应该像这样
do {
if (userNum < randNumber)
{
cout << "Number is Higher\n";
cin >> userNum;
}
else if (userNum > randNumber)
{
cout << "Number is Lower\n";
cin >> userNum;
}
else if(userNum == randNumber)
{
cout << "Congrats You got it!\n";
}
} while (userNum != randNumber);