cout >> "Please enter a number\n";
这是错误的,std::ostreams
只提供operator<<
来插入格式化的d ATA。改为使用cout << "Please enter a number\n";
。
getline(cin x);
首先,你错过了一个,
,因为getline需要两个或三个参数。但由于x
是integer
而不是std::string
它仍然是错误的。想一想 - 你能存储一个整数内的文本行吗?改为使用cin >> x
。
int y = rand();
虽然这似乎没有错,但是有一个逻辑错误。 rand()
是一个伪随机数发生器。它使用种子作为起始值和某种算法(a*m + b
)。因此你必须指定一个起始值,也叫做种子。您可以使用srand()
来指定。相同的种子会产生相同的数字顺序,所以请使用类似srand(time(0))
的东西。
while x != y
if x < y;
使用括号。并放弃额外的;
。在您的程序中的流浪分号;
类似于空表达式。
编辑:工作代码:
#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;
}
如果这是家庭作业,请将其标记为此类。 – 2012-04-18 20:58:28
这里没有什么可调试的,因为你所有的问题看起来都是语法错误。 – Chad 2012-04-18 20:59:19
这不是家庭主妇,我不知道如何解决语法错误 – Foxic 2012-04-18 21:00:16