c++ - 为什么尽管我的函数和 cout 语句放置错误,我的程序仍能运行?

标签 c++ function

理想情况下,我的华氏函数的一些内容应该放在主函数中,但想尝试一下。我要求用户在华氏函数中输入,之后,我在cout之后调用了华氏函数。陈述。我期望首先显示“您的温度...”字符串,但它在继续打印字符串之前要求输入。为什么会这样?

#include <iostream>
using namespace std;
int FahrenheitConv();
int main ()
{
    cout << "Your temperature in Fahrenheit is "<< FahrenheitConv();
    return 0;
}

int FahrenheitConv()
{
    double centigrade;
    cout << "What is your temperature in centigrade: ";
    cin >> centigrade;

    double fahrenheit = (1.8) * (centigrade ) + 32;
    return fahrenheit;
}

最佳答案

根据N4296 :

1.9 Program Execution [intro.execution]

[...] Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [ Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations.end note ] [...]

因此,您不能真正期望任何特定的顺序,除非对于真正特定的情况,例如逻辑运算符和三元运算符,它们引入了序列点。

关于c++ - 为什么尽管我的函数和 cout 语句放置错误,我的程序仍能运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48787409/

相关文章:

python - 动态函数创建和函数体评估

c++ - 传递智能指针的更简洁的替代方案

javascript - 调用 Math.random() 的函数是纯函数吗?

function - rust 封闭和fn不匹配

c++ - 是否存在需要在内存中创建对象到某个地址的情况?

php - PHP 中一个函数可以有多种返回值类型吗?

javascript - jQuery,使用for循环来操作元素? (添加/删除类(class)等)

c++ - 将下界与对象指针的 vector 一起使用

python - 重新设置小部件pyqt的布局

c# - Visual Studio 2010 编辑器意外自动更正