簡體   English   中英

使用cin不被接受C++輸入

[英]C++ input not being accepted using cin

我剛剛開始編程,我嘗試編寫一個簡單的程序來檢查數字是否為偶數,如果是則打印 YES,否則打印 NO。

#include <iostream>
using namespace std;

int main()
{
    int w;
    int remainder;
    
    cout << "Enter the number : ";
    
    cin >> w ; 
    remainder = w % 4;
    
    if(remainder==0) 
        cout << "\nYes " << endl; 
    
    else
        cout << "\nNO " << endl; 


    return 0;
}

當我嘗試運行此程序時,出現以下輸出:

$g++ -o main *.cpp
$main
Enter the number : 
Yes 

我在這里做錯了什么?

那里有一個邏輯錯誤。

remainder = w% 2;  // must be.

您報告的問題可能與您使用的程序有關。 我正在使用 Visual Studio,它沒有給我帶來任何問題。 但您也可以使用括號編寫條件:

if(remainder==0) {
    cout << "\nYes " << endl; 
}
else {
    cout << "\nNO " << endl; 
}

並試用它們。 也許有效。 (為什么可能?你上的在線編譯器的工作。在這種情況下,我不能保證任何東西)


為什么 %2

例如:“2% 4”會回答 2。這有時會導致在線編譯器出現問題。 最合乎邏輯的事情是通過執行“% 2”得到一個簡單的答案。 2% 2 = 0 這給了我們一個更平滑的答案。

1% 2 = 1,
2% 2 = 0,
3% 2 = 1

1 表示:不是偶數。 0 表示:偶數。


最好的方法是不要嘗試修復在線編譯器錯誤。 因為如果你為一個損壞的編譯器開發你的代碼,那么你會遇到一個像樣的編譯器的問題。 我建議使用普通的非在線編譯器。

用睡眠功能解決了問題並不一定意味着你已經解決了問題。 在開發更大的程序時,這條路徑會給你帶來很多問題。

嘗試使用這個..

#include<iostream>
using namespace std;
int main()
{
    int w;
    cout<<"Enter the number : ";
    cin>>w;
    string s=(w%2==0)?"even number":"odd number";
    cout<<w<<" is a "<<s;
    return 0;
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM