条件表达式中的模
Modulo in a conditional expression
我对编程很陌生,从比约恩的书《编程原理与实践c++》第二版开始。练习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 << " numbern";
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) res = "odd";
只是的一个相当简洁的版本
if (val%2) {
res = "odd";
}
请注意,if(...)
实际上不在乎值是"true"还是"false"。它只检查零还是非零。所以它相当于
if( val%2 != 0)
第二条命令行:string res = (val%2) ? "even" : "odd";
similary是写的一种简短方式
string res;
if(val%2 != 0){
res = "even";
}
else{
res = "odd";
}
这类命令的语法为condition ? value_if_true : value_if_false
添加到前面的答案中,您必须注意布尔值(或"true"值)是0和1,(在布尔代数中0为假,1为真)
因此,当
string res = (val % 2) ? "even" : "odd";
请注意,当您给定奇数时,它将始终返回数字1,这是"true",反之亦然。
你必须扭转这些局面,程序才能运行。
他只是不写多个括号,根本不使用它们
string res = "even"; //default value
if (val%2) res = "odd"; //in case it is odd, value changes
//output or threat in some way value.
而是
string res = (val%2) ? "even" : "odd";
简单地写一个你以前写过的if/else
的简短方法。
相关文章:
- 优化/减少 if 语句中的条件表达式
- 实现基于数字值(正、负、零)的条件表达式的最佳方法
- C++多个正则表达式条件语法
- 如何使用条件表达式返回对象指针?
- 如何将特征张量的值作为'if'条件表达式
- 变量在常量表达式中可用的条件
- 有条件地忽略 c++11 正则表达式中的大小写
- 对条件表达式结果的赋值(其中第二个和第三个操作数是相同类型和值类别的变量)是否仍然存在?
- 类简单分数的不可接受的条件表达式
- 如何在条件表达式中使用 'cin' 正确退出 while 循环?(C++,CLion)
- 条件表达式解析新表达式中详细阐述的类型说明符时出错
- 逗号(,)在条件部分中两个表达式之间的for循环中的工作方式
- 是“警告 C4127”(条件表达式是常量)曾经有帮助
- 是条件表达式C++总是布尔类型
- 条件断点:此表达式具有副作用,不会计算
- 是否可以将多个关系表达式放入 for 循环的测试条件中
- LAMBDA 错误:类型 'void' 的条件表达式是非法的
- 条件语句在比较表达式时的基础是什么?
- 条件表达式中的右值引用
- 声明不能发生在条件运算符表达式内部