简体   繁体   English

c ++ cout与float产生奇怪的结果

[英]c++ cout with float producing strange results

Currently I have the following: 目前,我有以下内容:

float some_function(){
    float percentage = 100;
    std::cout << "percentage = " << percentage;

    //more code
    return 0;
}

which gives the output 这给出了输出

percentage = 100

However when I add some std::endl like so: 但是,当我像这样添加一些std :: endl时:

float some_function(){
    float percentage = 100;
    std::cout << "percentage = " << percentage  << std::endl;

    //more code
    return 0;
}

This gives the output: 这给出了输出:

percentage = 1000x6580a8

Adding more endl's just prints out more 0x6580a8's. 添加更多endl仅会打印出更多0x6580a8。

What could be causing this? 是什么原因造成的? This is compiled with gcc 4.4.3 on Ubuntu 10.04. 这是在Ubuntu 10.04上使用gcc 4.4.3编译的。

The function is written correctly. 该函数编写正确。 On my machine ( g++ 4.4.3 on Ubuntu 10.04 ) everything works smoothly. 在我的机器上(Ubuntu 10.04上的g ++ 4.4.3),一切运行正常。 Are you sure that the error isn't caused by some other part of the code ? 您确定错误不是由代码的其他部分引起的吗?

Your code is perfectly valid. 您的代码是完全有效的。 I suspect that you could be smashing your stack or heap in some other part of your code as the most likely cause. 我怀疑您可能是在代码的其他部分破坏堆栈或堆,这是最可能的原因。 0x6580a8 is too short to be an object address. 0x6580a8太短,无法成为对象地址。 Also, he would never get the same address in two runs of the same program. 而且,他永远不会在同一程序的两次运行中获得相同的地址。

如果您尝试\\ n怎么办?

std::cout << "percentage = " << percentage  << "\n";

Is this your actual code, or is there a different sort of stream instead of cout ? 这是您的实际代码吗?或者是否有其他类型的流而不是cout

It's taking the address of the endl manipulator instead of applying it to the stream, which implies that it can't see the matching version of endl for the stream type you're using. 它使用的是endl机械手的地址,而不是将其应用于流,这意味着它无法看到所使用的流类型的endl匹配版本。

What happens if you use << "\\n" << std::flush instead? 如果使用<< "\\n" << std::flush会发生什么?

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

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