当同时使用 cout 和 printf 时,C++ 没有像它应该的那样四舍五入

C++ not rounding as it should when using both cout and printf

我需要制作一个计算 cos(x) 的程序,我的问题是当我使用 printf 例如 cos(0.2) 是 0.98 但结果是 0.984 并且它没有四舍五入到 2数字。

我的代码:

#include <iostream> 
#include <math.h>

using namespace std;

int main()
{
    float x = 0.2;
    cout << "x=" << x << " cos(y) y=" << printf("%.2f", cos(x)) << "\n";
    return 0;
}

正如其他人在评论中所说,混合使用 std::coutprintf 并不能满足您的要求。而是使用流操纵器 std::fixedstd::setprecision:

#include <iomanip>  //Required for std::fixed and std::precision
#include <iostream> 
#include <cmath> //Notice corrected include, this is the C++ version of <math.h>

using namespace std;

int main()
{
    float x = 0.2f; //Initialize with a float instead of silently converting from a double to a float.
    cout << "x=" << x << " cos(y) y=" << std::fixed << std::setprecision(2) << cos(x) << "\n";
    return 0;
}

问题不在于四舍五入数字,而在于输出。

cout << "x=" << x << " cos(y) y=" << printf("%.2f", cos(x)) << "\n";

这里您混合了两种写入标准输出的方法。将对 printf 的调用插入 cout << 将输出 return 值 printf 恰好是 4 和同时输出一些东西作为副作用。

因此创建了两个输出:

  • 将值流式传输到 cout 输出 x=0.2 cos(y) y=4
  • 调用 printf(正确)输出 0.98

两个输出可能混在一起,给人的印象是结果是 0.984:

x=0.2 cos(y) y=    4
               ^^^^
               0.98

可以同时使用coutprintf,但您不应混淆return值[= printf 的 49=] 及其作为 副作用创建的输出 :

cout << "x=" << x << " cos(y) y=";
printf("%.2f\n", cos(x));

应该输出

x=0.2 cos(y) y=0.98

另请参阅:C++ mixing printf and cout