【发布时间】:2015-12-04 21:48:23
【问题描述】:
我对编程非常陌生,我从 Bjourne 的书开始:编程原理和实践 C++ 第 2 版。习题 8 第 3 章他要求:
“编写一个程序来测试一个整数值以确定它是奇数还是偶数......提示:请参阅第 3.4 节中的余数(模)运算符。”
我可以这样做:
int main() {
int n;
cout << "Enter an integer: ";
cin >> n;
if ( n%2 == 0) {
cout << n << " is even.";
}
else {
cout << n << " is odd.";
}
return 0;
}
但他在自己的网站上给出了自己的解决方案:
int main()
{
int val = 0;
cout << "Please enter an integer: ";
cin >> val;;
if (!cin) error("something went bad with the read");
string res = "even";
if (val%2) res = "odd";
cout << "The value " << val << " is an " << res << " number\n";
keep_window_open();
}
catch (runtime_error e) {
cout << e.what() << '\n';
keep_window_open("~");
}
/*
Note the technique of picking a default value for the result ("even") and changing it only
if needed.
The alternative would be to use a conditional expression and write
string res = (val%2) ? "even" : "odd";
什么是
string res = "even";
if (val%2) res = "odd";
和
string res = (val%2) ? "even" : "odd";
真的在做什么?我以前没见过他在书中解释过这些。此外,最后一个代码,当我输入偶数时它给我“奇数”结果,当我输入奇数时它给我一个“偶数”结果。到底是怎么回事?抱歉发了这么长的帖子,希望我能解释一下我需要什么...
【问题讨论】:
-
我可以理解你之前没有见过三元运算符,但你想知道
if是做什么的吗? -
也许我无法理解 (val%2) 是如何在 If 语句中作为条件工作的......
-
好吧,你现在可以了。你有答案。
-
if(x)表示if( (x) != 0 ),其中x是任意表达式 -
太棒了,谢谢伙计!