大佬教程收集整理的这篇文章主要介绍了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";
这里混合了两种写入标准输出的方法。将对 printf
的调用插入 cout <<
将输出 printf
的 返回值,恰好是 4
,同时输出一些内容为一个副作用。
因此创建了两个输出:
cout
输出 x=0.2 cos(y) y=4
printf
(正确)输出 0.98
两个输出可能相互混合,造成结果为 0.984
的印象:
x=0.2 cos(y) y= 4
^^^^
0.98
您可以同时使用cout
和printf
,但您不应将printf
的返回值与输出混淆它会产生副作用:
cout << "x=" << x << " cos(y) y=";
printf("%.2f\n",cos(X));
应该输出
x=0.2 cos(y) y=0.98
另见:C++ mixing printf and cout
,正如其他人在评论中所说,混合 std::cout
和 printf
并不能满足您的需求。而是使用流操作符 std::fixed
和 std::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;
}
以上是大佬教程为你收集整理的C++ 在使用 cout 和 printf 时不四舍五入全部内容,希望文章能够帮你解决C++ 在使用 cout 和 printf 时不四舍五入所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。