适当的三元运算符格式

Red*_*One 6 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"
        : "";
Run Code Online (Sandbox Code Playgroud)

我想要它做的是:

    // 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;
Run Code Online (Sandbox Code Playgroud)

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

小智 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
Run Code Online (Sandbox Code Playgroud)

正确的代码:

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!*/
Run Code Online (Sandbox Code Playgroud)