调试还不是很好,但是我遇到了一些错误.一些预期'('')'和';' 另外'else'没有先前的'if',在cout中与'operator >>不匹配
我知道这很容易,但仍然试图让我的脚踏上门.谢谢 :)
#include <iostream>
#include <cstdlib>
using namespace std;
int main() // guess number game
{
int x;
cout >> "Please enter a number\n";
getline(cin x);
int y = rand();
while x != y
{
if x < y;
cout >> "Go higher";
else;
cout >> "Go lower";
}
}
Run Code Online (Sandbox Code Playgroud)
cout >> "Please enter a number\n";
Run Code Online (Sandbox Code Playgroud)
这是错误的,std::ostreams只提供operator<<插入格式化数据.请cout << "Please enter a number\n";改用.
getline(cin x);
Run Code Online (Sandbox Code Playgroud)
首先,你错过了一个,,因为getline需要两个或三个参数.但既然x是一个integer而不是std::string它仍然是错误的.想一想 - 你能在一个整数内存储一个文本行吗?请cin >> x改用.
int y = rand();
Run Code Online (Sandbox Code Playgroud)
虽然这似乎没有错,但是存在逻辑错误.rand()是一个伪随机数发生器.它使用种子作为起始值和某种算法(a*m + b).因此,您必须指定一个起始值,也称为种子.您可以使用指定srand().相同的种子将导致相同的数字顺序,所以使用类似的东西srand(time(0)).
while x != y
if x < y;
Run Code Online (Sandbox Code Playgroud)
使用括号.并删除额外的;.程序中的杂散分号;类似于空表达式.
编辑:工作代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main(){
int x;
int y;
srand(time(0));
y = rand();
std::cout << "Please enter a number: ";
do{
if(std::cin >> x){
if(x < y)
std::cout << "Go higher: ";
if(x > y)
std::cout << "Go lower: ";
}
else{
// If the extraction fails, `std::cin` will evaluate to false
std::cout << "That wasn't a number, try again: ";
std::cin.clear(); // Clear the fail bits
}
}while(x != y);
std::cout << "Congratulations, you guessed my number :)";
return 0;
}
Run Code Online (Sandbox Code Playgroud)