简体   繁体   English

奇怪的编译器行为

[英]Strange compiler behavior

I just hit a strange behavior when compiling a small C++ program with g++ (4.6.3). 使用g ++(4.6.3)编译小型C ++程序时,我只是遇到了一个奇怪的行为。 Compare the two floats celsius and test: 比较两个浮点摄氏温度并测试:

#include <iostream>
using namespace std;

int main () {
    float fahrenheit = 0;
    float celsius = 0;
    float test = 0;

    cout << "Temperature in °F: " << endl;
    cin >> fahrenheit;

    celsius = 5 / 9 * (fahrenheit - 32);
    test =  5 * (fahrenheit - 32) / 9;

    cout << "\nWrong:\t" << fahrenheit << " °F = " << celsius << " °C" << endl;
    cout << "Correct:" << fahrenheit << " °F = " << test << " °C" << endl;
}

I compiled this with just "g++ test.cpp -o test". 我仅使用“ g ++ test.cpp -o test”进行了编译。

This is the output of the program: 这是程序的输出:

$ ./test
Temperature in °F: 
1000

Wrong:  1000 °F = 0 °C
Correct:1000 °F = 537.778 °C

Can someone explain to me why g++ does (reproducibly) compute celsius to 0, whereas test contains the correct solution? 有人可以向我解释为什么g ++(可重复)将摄氏度计算为0,而测试包含正确的解决方案吗? Does it have anything to do with some optimization, although I didn't set any args for that? 尽管我没有为此设置任何参数,但它与某些优化有关吗? Or is this really a bug in some way? 还是这确实是某种方式的错误?

5 / 9 = 0 5 / 9 = 0

0 * anything = 0 0 * = 0

When you divide to integers, you get an integer back. 当您除以整数时,您会得到一个整数。 You can just say 5.0 / 9 and it should be a lot better. 您只能说5.0 / 9 ,应该会好很多。

When you're writing code and don't get what you expect, your first inclination should be "what dod I do wrong?" 当您编写代码而没有得到期望的结果时,您的第一个倾向应该是“ 做错了什么?” not "what did the compiler do wrong?" 不是“编译器做错了什么?”

It'll help you look in the right place most of the time. 它可以帮助您在大多数时间寻找正确的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM