gpt4 book ai didi

c++ - 从 double* 转换为 int 会失去精度

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:38:35 25 4
gpt4 key购买 nike

d 是一个double 类型的数据,p 是指向它的指针。当它们都显式地分别转换为 int 时,它会为指针 p 的转换提供以下错误。:从 double* 转换为 int 会丢失精度

#include<iostream>
using namespace std;
int main()
{
int i,j;
double d=3.5;
double* p=&d;
i=(int)d;
j=(int)p; // this line gives the error
cout<<i<<" "<<j;
return 0;
}

我预计会出现错误“从 double*int 的无效转换。为什么不是这样?

此外,如果对指针 p 进行数据 d 的转换,为什么没有给出“丢失精度”错误?

最佳答案

I expected the error there to be "invalid conversion from 'double*' to'int'". Why is it not so?

我认为这只是一种依赖于编译器的处理此错误的方法。在 clang 上,我得到了类似的东西,也许信息量更大:

error: cast from pointer to smaller type 'int' loses information

Also, why didn't the cast for data d give the "loses precision" errorif it does so for the pointer p?

从 float 或 double 到 int 的转换属于标准转换,不会出错并且有时很有用。这不应该引发错误,更多信息 here ,

A prvalue of floating-point type can beconverted to a prvalue of any integer type. The fractional part istruncated, that is, the fractional part is discarded. If the valuecannot fit into the destination type, the behavior is undefined (evenwhen the destination type is unsigned, modulo arithmetic does notapply). If the destination type is bool, this is a boolean conversion(see below).

A prvalue of integer or unscoped enumeration type can beconverted to a prvalue of any floating-point type. If the value cannotbe represented correctly, it is implementation defined whether theclosest higher or the closest lower representable value will beselected, although if IEEE arithmetic is supported, rounding defaultsto nearest. If the value cannot fit into the destination type, thebehavior is undefined. If the source type is bool, the value false isconverted to zero, and the value true is converted to one.

关于c++ - 从 double* 转换为 int 会失去精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56497318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com