一个值为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++?
我需要将表达式的类型从浮点更改为整数,以便将其添加到另一个整数变量中。表达式的实际值为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
仍然很好奇这有什么不同?
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 程序崩溃并显示"std::out_of_range"错误
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 从数据库实时显示QT c++中的数据
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 显示错误输出的简单数组排序程序
- Qt自定义QPush按钮未显示在布局上
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- 显示基于用户输入的整数的字符
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 密码登录程序将永远循环并显示不正确的结果
- std::strftime 在 Windows 中使用 GMTIME 将时区 UTC 显示为 UTC+1