【问题标题】:C++ not rounding as it should when using both cout and printf当同时使用 cout 和 printf 时,C++ 没有四舍五入
【发布时间】: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 &lt;&lt; "x=" &lt;&lt; x &lt;&lt; " cos(y) y=" &lt;&lt; std::fixed &lt;&lt; std::setprecision(2) &lt;&lt; cos(x) &lt;&lt; "\n";

标签: c++ io


【解决方案1】:

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

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

在这里,您混合了两种写入标准输出的方法。将对printf 的调用插入cout &lt;&lt; 将输出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,但您不应将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

【讨论】:

  • (请注意,仅输出cos(x)=0.98 而不是cos(y) y=0.98 在数学上更有意义)
【解决方案2】:

正如其他人在 cmets 中所说,混合 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多