C++在使用cout和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;
}
回答
问题不在于对数字进行四舍五入,而在于输出。
cout << "x=" << x << " cos(y) y=" << printf("%.2f", cos(x)) << "n";
在这里,您混合了两种写入标准输出的方法。插入对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";
您可以同时使用cout和printf,但你不应该混淆返回值的printf用它创建为输出的副作用:
cout << "x=" << x << " cos(y) y=";
printf("%.2fn", cos(x));
应该输出
x=0.2 cos(y) y= 4
^^^^
0.98
另请参阅:C++ 混合 printf 和 cout