gpt4 book ai didi

c++ - C++ 函数中出现奇怪的舍入

转载 作者:太空宇宙 更新时间:2023-11-04 12:04:22 24 4
gpt4 key购买 nike

我正在用 C++ 编写一个函数,它应该在传递的数字 (inputValue) 中找到最大的单个数字。例如,.345 的答案是 5。但是,一段时间后,程序将 inputValue 更改为类似于 .3449 的值(然后最大数字设置为 9)。我不知道为什么会这样。将不胜感激解决此问题的任何帮助。

这是我的 .hpp 文件中的函数

void LargeInput(const double inputValue)
//Function to find the largest value of the input
{
int tempMax = 0,//Value that the temporary max number is in loop
digit = 0,//Value of numbers after the decimal place
test = 0,
powerOten = 10;//Number multiplied by so that the next digit can be checked
double number = inputValue;//A variable that can be changed in the function
cout << "The number is still " << number << endl;
for (int k = 1; k <= 6; k++)
{
test = (number*powerOten);
cout << "test: " << test << endl;
digit = test % 10;
cout << (static_cast<int>(number*powerOten)) << endl;
if (tempMax < digit)
tempMax = digit;
powerOten *= 10;
}
return;
}

最佳答案

您无法在计算机中精确表示实数( double )——它们需要近似。如果您更改函数以处理 long 或 int,则不会有任何不准确之处。这对于你的问题的上下文来说似乎很自然,你只是在看数字而不是数字,所以 .345 可以是 345 并得到相同的结果。

试试这个:

int get_largest_digit(int n) {
int largest = 0;

while (n > 0) {
int x = n % 10;
if (x > largest) largest = x;
n /= 10;
}
return largest;
}

关于c++ - C++ 函数中出现奇怪的舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12850673/

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