即时尝试学习c ++并且无法弄清楚这个错误的原因它似乎与我没有得到任何错误的其他cout行相匹配
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int number = 42;
int guess;
bool notguessed = true;
while (notguessed);
cout << "Guess my number";
cin >> "Guess";
if (guess == number)
{
cout << "You got it" << endl;
notguessed = false;
}
if (guess < number)
{
cout << "To low try again" << endl;
}
if (guess > number)
{
cout << "To high try again" << endl;
}
return 0;
}
答案 0 :(得分:1)
试试这段代码: -
# your code goes here
#include <iostream>
using namespace std;
int main()
{
int number = 42;
int guess;
bool notguessed = true;
cout << "Guess my number";
while (notguessed)
{
cin >> guess;
if (guess == number)
{
cout << "You got it" << endl;
notguessed = false;
}
if (guess < number)
{
cout << "To low try again" << endl;
}
if (guess > number)
{
cout << "To high try again" << endl;
}
}
return 0;
}
你试图输入一个字符串“猜猜”。将其更改为cin&gt;&gt; guess。 并更改while循环分号。
答案 1 :(得分:0)
cin >> "Guess";
应该是
cin >> guess;
答案 2 :(得分:0)
在第10行进行更改 while循环; 去掉 ; 提供一些 while(condition){// do code}
在第13行进行更改
{{1}}
答案 3 :(得分:0)
您的程序有两个错误 - 编译错误和逻辑错误。
编译错误 - 考虑此代码段 -
cin >> "Guess";
在这里,您尝试为常量赋值。你打算做的是 -
cin>>guess
逻辑错误 - 当您进行上述更改时,您的代码将正常编译,但无法按照您的意愿运行,这是因为以下行 -
while (notguessed);
上面的while循环将无限运行,notguessed
为true
,并且循环中的值不会被修改。
将其更改为 -
while (notguessed){
cout << "Guess my number";
cin >> guess;
if (guess == number)
{
cout << "You got it" << endl;
notguessed = false;
}
else if (guess < number)
{
cout << "Too low try again" << endl;
}
else
{
cout << "Too high try again" << endl;
}
}
注意 - 我将您的简单if
语句转换为if else if
,这是为了避免在一个if
时对其他if
进行不必要的检查已评估为true
。
通过使用notguessed
关键字 -
break
while (true){
cout << "Guess my number";
cin >> guess;
if (guess == number)
{
cout << "You got it" << endl;
break;
}
else if (guess < number)
{
cout << "Too low try again" << endl;
}
else
{
cout << "Too high try again" << endl;
}
}