gpt4 book ai didi

C++ 精确除法会失去精度吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:11:31 26 4
gpt4 key购买 nike

Q1:一个整数除以它的约数会失去精度吗?

int a=M*N,b=N;//M and N are random non-zero integers.
float c=float(a)/b;
if (c==M)
cout<<"accurate"<<endl;

Q2:传递一个浮点值会失去精度吗?

float a=K;//K is a random float;
if (a==K)
cout<<"accurate"<<endl;

最佳答案

Q1:Will dividing a integer by its divisor lose precision ?

是的。我使用以下程序得出了一些数字:

#include <iostream>
#include <climits>

int main()
{
int M = 10;
int N = 7;
int inaccurateCount = 0;
for (; M < INT_MAX && inaccurateCount < 10; ++M )
{
int a = M*N;
float c = float(a)/N;
if ( c != M )
{
std::cout << "Not accurate for M: " << M << " and N: " << N << std::endl;
inaccurateCount++;
}
}

return 0;
}

这是输出:

Not accurate for M: 2396747 and N: 7
Not accurate for M: 2396749 and N: 7
Not accurate for M: 2396751 and N: 7
Not accurate for M: 2396753 and N: 7
Not accurate for M: 2396755 and N: 7
Not accurate for M: 2396757 and N: 7
Not accurate for M: 2396759 and N: 7
Not accurate for M: 2396761 and N: 7
Not accurate for M: 2396763 and N: 7
Not accurate for M: 2396765 and N: 7

Q2:Will passing a float value lose precision ?

不,不应该。

关于C++ 精确除法会失去精度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33795906/

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