[英]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.