适当的三元运算符格式

时间:2016-03-06 01:04:52

标签: c++ ternary-operator

这就是我所拥有的。我不确定如何正确地写它。我试过谷歌搜索,但无济于事。请不要畏缩太多:

cout << (guess > randomNumber) ? "\nWhoops! Try again!\n You guessed higher than the random number!\n\n"
        : (guess < randomNumber) ? "\nWhoops! Try again!\n You guessed lower than the random number!\n\n"
        : "";

我想要它做的是:

    // Gives hint that inputted number is higher or lower
    // than inputted number
    if (guess > randomNumber)
        cout << "\nWhoops! Try again!"
        << " You guessed higher than the random number!\n"
        << endl;
    else if (guess < randomNumber)
        cout << "\nWhoops! Try again!"
        << " You guessed lower than the random number!\n"
        << endl;

任何帮助将不胜感激。我只是想学习如何编写我的程序以提高效率和更小。非常感谢任何反馈。

2 个答案:

答案 0 :(得分:4)

在整个表达式周围放置一些括号,否则最终会打印布尔值:

int guess = 10;
    int randomNumber = 9;

    cout << (guess > randomNumber) ? "\nWhoops! Try again!\n You guessed higher than the random number!\n\n"
            : (guess < randomNumber) ? "\nWhoops! Try again!\n You guessed lower than the random number!\n\n"
            : "" ;

// Output: 1

正确的代码:

int guess = 10;
    int randomNumber = 9;

    cout << ( (guess > randomNumber) ? "\nWhoops! Try again!\n You guessed higher than the random number!\n\n"
            : (guess < randomNumber) ? "\nWhoops! Try again!\n You guessed lower than the random number!\n\n"
            : "" ); // Notice the brackets!

/*Output:
Whoops! Try again!
You guessed higher than the random number!*/

答案 1 :(得分:1)

  

效率更高

与您在那里做的事情无关(如果“有效”则表示更好的运行时特性)。

  

一个不起眼的目标,但如果可读性因此而失败(如果由于句法的复杂性而失去括号......最终结果是错误的。)

请记住:代码是为人类阅读而编写的。

您应该坚持使用您在问题中显示的ifelse方法。也就是说,恕我直言“好”的方法(如果你真的需要对此进行抽象)将把它打包成一些函数:

template<class T, class X, class Y, class Z>
void comp_if(T value, T reference, X less, Y equal, Z greater) {
  if (value < reference) less();
  else if (value > reference) greater();
  else equal();
}

一样使用
// missing real macros a lot
comp_if(foo, bar,
  []() {cout << "less"; },
  []() {cout << "equal";},
  []() {cout << "greater"});

这是否真的有助于提高可读性是我留给读者做出的选择。