[英]If statements in c++ doubles
#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <stdlib.h>
using namespace std;
int main()
{
int x,y,z;
cout<<"welcome to guessing game\nplayer one pick your number: ";
cin>>x;
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
Sleep(2000);
system("cls");
cout<<"ok player 2 pick the guess";
cin>>y;
if (x == y){
cout<<"congrats you got it right";
}
else{
if (x < y){
cout<<"Go lower";}
else {
if (x > y){
cout<<"higher";}}
}
system("pause>nul");
return 0;
}
我無法看到獲取初始if語句無論我輸入什么號碼都會自動顯示超出數字范圍。 我也允許像if(x <0)(x> 100)那樣放置像soo這樣的條件。 我怎么做它洙它回到程序的開始?
有一個錯誤:
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
應該:
if (x < 0 || x > 100)
{
cout<<"out of number range";
}
你還需要處理你的縮進; 那些對底部的if
/ else
語句看起來很狡猾(由於縮進,我無法真正說出來)。
除了編寫if (x < 0 || x > 100)
(並刪除分號)之外,您應該警惕比較浮點上的相等性。 if (x == y){
在審核你的代碼時,我會用紅色標記你的行。
請參見浮點比較
沒有其他人真正回答你的第二個問題:如何循環它,你走了:
int x;
cout << "Welcome to the guessing game\n";
do {
cout << "Please enter a number from 0 to 100: ";
cin >> x;
} while (x < 0 || x > 100);
你寫
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
首先刪除半結腸。 你的意思是第二個
if ((x < 0) || (x > 100))
{
cout<<"out of number range";
}
嘗試這個:
/*
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
*/
if (x < 0 || x > 100)
{
cout<<"out of number range";
}
有一些值得注意的語法錯誤:
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
首先,你不能像我所知道的那樣在C ++中並排放置兩個條件。 你必須用||
分開它們 對於OR,或者&&
對於AND(在大多數情況下 - 還有其他一些)。
還有,你有一個;
在你的if語句結束時。 我相信在C ++中這樣做也會導致一些問題。
您的最終代碼應如下所示:
if ((x < 0) || (x > 100))
{
cout << "out of number range" << endl;
}
<< endl;
部分是可選的。 這會為您的輸出添加一個新行,以便在下次編寫內容時提高可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.