条件表达式中的模

Modulo in a conditional expression

本文关键字:表达式 条件      更新时间:2023-10-16

我对编程很陌生,从比约恩的书《编程原理与实践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的简短方法。