cout >> "Please enter a number\n";
これは間違っています。フォーマットされたデータを挿入std::ostreams
するための のみを提供してください。代わりにoperator<<
使用してください。cout << "Please enter a number\n";
getline(cin x);
,
まず、getlineには 2 つまたは 3 つの引数が必要なため、 がありません。しかし、x
is でinteger
あり、 a ではないので、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;
}