C++ 在使用 cout 和 printf 时不四舍五入

-4 c++ io

我需要制作一个计算 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;
}
Run Code Online (Sandbox Code Playgroud)

mkr*_*er1 5

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

cout << "x=" << x << " cos(y) y=" << printf("%.2f", cos(x)) << "\n";
Run Code Online (Sandbox Code Playgroud)

在这里,您混合了两种写入标准输出的方法。插入对printfinto的调用cout <<将输出恰好是的返回值,同时输出一些作为副作用的东西。printf4

因此创建了两个输出:

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

这两个输出可能相互混合,给人的印象是结果是0.984

cout << "x=" << x << " cos(y) y=" << printf("%.2f", cos(x)) << "\n";
Run Code Online (Sandbox Code Playgroud)

可以同时使用coutprintf,但你不应该混淆返回值printf用它创建为输出的副作用

cout << "x=" << x << " cos(y) y=";
printf("%.2f\n", cos(x));
Run Code Online (Sandbox Code Playgroud)

应该输出

x=0.2 cos(y) y=    4
               ^^^^
               0.98
Run Code Online (Sandbox Code Playgroud)

另请参阅:C++ 混合 printf 和 cout