gpt4 book ai didi

c++ - 在 C++ 中转换没有按预期工作

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

这个小程序是用来计算一个 2 位数字的第一位和第二位数字的。但是,当我尝试在数字 99 上使用它时,它会打印 9 和 8,但其他 2 位数字似乎工作正常。这可能是微不足道的,但我在编程方面相对较新。

#include <iostream>

using namespace std;

void test(int num) {

float numValue = (num*1.0) / 10;
cout << numValue << endl;
// prints 9.9

int firstDigit = num / 10;
cout << firstDigit << endl;
// prints 9

int secondDigit = (numValue - firstDigit) * 10;
cout << secondDigit << endl;
// prints 8, supposed to be (9.9 - 9) * 10

}

int main()
{
test(99);
return 0;
}

最佳答案

发生这种情况是因为 (numValue - firstDigit) 不完全是 0.9,而是 0.89999...,因为 float 通常不准确。因此,当您将 0.8999... 乘以 10 时,您会得到 8.999... 的结果 但是,您会将其放入 int 变量,所以它被修剪并正好变成 8。

虽然您的确切任务并不真的需要浮点运算,使用整数就足够了。

关于c++ - 在 C++ 中转换没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15630414/

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