简体   繁体   English

C++ 在同时使用 cout 和 printf 时没有四舍五入

[英]C++ not rounding as it should when using both cout and printf

I need to make a program that calculates cos(x) and my problem is that when I use printf for example cos(0.2) is 0.98 but it comes out as 0.984 and it's not rounding to 2 numbers.我需要制作一个计算 cos(x) 的程序,我的问题是,当我使用printf时,例如 cos(0.2) 为 0.98,但结果为 0.984,并且没有四舍五入为 2 个数字。

My code:我的代码:

#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;
}

The problem is not with rounding the numbers, but with output.问题不在于四舍五入,而在于 output。

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

Here you are mixing two ways to write to the standard output.在这里,您混合了两种写入标准 output 的方法。 Inserting a call to printf into cout << will output the return value of printf which happens to be 4 and at the same time output something as a side effect. Inserting a call to printf into cout << will output the return value of printf which happens to be 4 and at the same time output something as a side effect.

So two outputs are created:因此创建了两个输出:

  • Streaming values into cout outputs x=0.2 cos(y) y=4将值流式传输到cout输出x=0.2 cos(y) y=4
  • Calling printf (correctly) outputs 0.98调用printf (正确)输出0.98

It is possible that the two outputs are mingled with each other, creating the impression that the result was 0.984 :这两个输出可能相互混合,给人的印象是结果是0.984

x=0.2 cos(y) y=    4
               ^^^^
               0.98

You can use both cout and printf , but you should not confuse the return value of printf with the output it creates as a side effect :可以同时使用coutprintf ,但不应将 printf 的返回值与它作为副作用创建的printf混淆:

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

should output应该 output

x=0.2 cos(y) y=0.98

See also: C++ mixing printf and cout另见: C++ 混合 printf 和 cout

As others have said in the comments, mixing std::cout and printf does not do what you want.正如其他人在评论中所说,混合std::coutprintf并不能满足您的要求。 Instead use the stream manipulators std::fixed and std::setprecision :而是使用 stream 操纵器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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM