【发布时间】:2021-03-14 20:34:56
【问题描述】:
我需要编写一个计算 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;
}
【问题讨论】:
-
我不确定
printf的返回值是否应该放入流中。 -
printf 返回一个整数,其中包含它写入的内容数量,但如果您同时使用 printf 和 cout ,除非您确定缓冲区已同步,否则它会弄乱您的打印。如果您确实想在流中设置精度,可以使用stackoverflow.com/questions/22515592/…
-
要么这样做:
printf("x=%f cos(y) y=%2f\n",x,cos(x));,要么这样做:cout << "x=" << x << " cos(y) y=" << std::fixed << std::setprecision(2) << cos(x) << "\n";