【发布时间】:2020-07-10 01:39:06
【问题描述】:
所以我写了这个小练习程序,告诉你在给定的数量下你需要多少五分钱和美分。我不明白为什么即使数学正确,程序也会输出 0 美分。我无法理解问题所在。
// Example program
#include <iostream>
using namespace std;
int main()
{
const double nickels{0.05};
const double cents{0.01};
int amt_needed_nickels{0}, amt_needed_cents{0};
double amt_val{0.06f}; // for 0.06 cents
double amt_val_copy{amt_val};
amt_needed_nickels = amt_val / nickels;
if(amt_needed_nickels != 0)
amt_val -= (nickels * amt_needed_nickels);
amt_needed_cents = amt_val / cents;
cout << "If it costs $" << amt_val_copy << ", you'll need:\nNickels: " << amt_needed_nickels << "\nCents: " << amt_needed_cents << "\n";
cout << "Even though amt_val is " << amt_val << ", and cents is also " << cents << ", and 0.01/0.01 does equal 1, why is amt_needed_cents not 1?\n";
}
公平地说,我知道如果我将 const double cents{0.01} 更改为 const float cents{0.01},并从 double amt_val{0.06f} 中删除 f;加倍 amt_val{0.06};它会起作用,但我不明白表面下到底发生了什么。为什么程序给上面的amt_needed_cents 0,而在其他情况下给1?
// Example program
#include <iostream>
using namespace std;
int main()
{
const double nickels{0.05};
const float cents{0.01};
int amt_needed_nickels{0}, amt_needed_cents{0};
double amt_val{0.06}; // for 0.06 cents
double amt_val_copy{amt_val};
amt_needed_nickels = amt_val / nickels;
if(amt_needed_nickels != 0)
amt_val -= (nickels * amt_needed_nickels);
amt_needed_cents = amt_val / cents;
cout << "If it costs $" << amt_val_copy << ", you'll need:\nNickels: " << amt_needed_nickels << "\nCents: " << amt_needed_cents << "\n";
cout << "I know this is correct, but I don't know what the compiler is thinking with this as compared to the other\n\n";
}
【问题讨论】:
-
我认为你希望这是一个浮点数而不是双精度数:
double amt_val{0.06f}; // for 0.06 cents。 0.0 默认为双倍。而 0.0f 是一个浮点数。 -
不要使用浮点数进行货币计算,因为浮点数并不精确。
0.01、0.05和0.06都没有精确的二进制表示。使用整数,如果不是,请使用支持货币计算的其他(第三方)数据类型。 -
是的,我认为这就是我刚刚想到的,例如 double var{0.0f} 与 float var{0.0} 相同吗?但这仍然不能让我理解为什么 float 和 double 会导致不同的值,但我想这只是一个需要注意的类型问题..?
-
0.0f明确是float。0.0被假定为double。没有理由使用f,除非您需要实际的float。 -
这能回答你的问题吗? Is floating point math broken?
标签: c++ floating-point double