一个值为1的浮点表达式在转换为int时显示0.如何在C++中消除这一点

A Floating point expression whose value is 1 shows 0 when converted to int. How to get rid of this isuue in C++?

本文关键字:显示 C++ 这一点 int 转换 一个 表达式      更新时间:2023-10-16

我需要将表达式的类型从浮点更改为整数,以便将其添加到另一个整数变量中。表达式的实际值为1。但是表达式值((d*s)/sqrt(1+pow(s,2))在从浮点变为int时显示0。因此,它给出了错误的结果。为什么它显示0?我如何避免这种情况?

#include <iostream>
#include <math.h>
using namespace std;
int main(){
    float d = sqrt(2);
    float s = sqrt(1);
    cout<<((d*s)/sqrt(1+pow(s, 2)))<<"n";  // **prints 1**
    cout<<(int) ((d*s)/sqrt(1+pow(s, 2)));  // **prints 0**
}

问题在于浮点表示。如果您打印以下内容:

#include <iostream>
#include <math.h>
using namespace std;
int main(){
    float d = sqrt(2);
    float s = sqrt(1);
    cout.precision(15);
    cout<<((d*s)/sqrt(1+pow(s, 2)))<<"n";  // **prints 1**
    cout<<(int) ((d*s)/sqrt(1+pow(s, 2)));  // **prints 0**
}

您将看到第一行打印0.999999982885729。当强制转换为int时,数字会被截断,因此为0。你必须先绕一圈。为此,更改最后一行:

cout<<(int) round(((d*s)/sqrt(1+pow(s, 2))));

int值将为1。

当我将表达式分配给一个变量(比如a),然后打印值时,不会出现这个问题。

float a = (d*s)/sqrt(1+pow(s, 2));
cout<<a;       // prints 1 
cout<<(int) a; // prints 1 again not 0

仍然很好奇这有什么不同?