c++ - float 减法问题

标签 c++ c

<分区>

这个程序必须计算最小数量的硬币,但它有一些错误,因为结果很奇怪。这可能是明显的错误,但我找不到。

int main(int argc,char* argv[]){
      float x;
      printf("How much cash in float number:");
      scanf("%f", &x);

      int quaters;
      while(x>=0.25){
        x-=0.25;
        quaters++;
      }
      printf("%f\n",x);

      int fives;
      while (x>=0.05){
        x-=0.05;
        fives++;
      }
       printf("%f\n",x);

      int one;
      while (x>=0.01){
        x-=0.01;
        one++;
      }
       printf("%f\n",x);
      printf("quaters %d\t fives %d\t ones %d\n", quaters, fives, one);
      return 0;
    }

输出是这样的

    How much cash in float number:0.41
0.160000
0.010000
0.010000
quaters 1    fives 3     ones 32764

怎么了?

最佳答案

使用前需要将quatersfivesone初始化为0:

int quaters=0;
....
int fives=0;
....
int one=0;
....

关于最后的 0.01 结果,谷歌搜索“比较浮点变量 C++”。即使在 SO 中,您也会找到大量相关帖子。

对于即时解决方案,由于您在小数点后最多使用 2 位数字,因此更改 float compare from

x>=0.25

x>0.249

相应地所有其他人:

x>0.049

x>0.009

关于c++ - float 减法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32710854/

相关文章:

c++ - 具有特征库的 MatrixFree-Matrix(和 Vector)乘积

c++ - typedef 的头文件最佳实践

c++ - 在 C++ 中显式设置 union 中的事件成员

c++ - graphics.h 没有输出

php - 将 LaTeX 渲染为图像

c++ - 在 sapi5 speak 函数中存储一个保存用户输入数据的变量

c - 链接 c 项目时体系结构 x86_64 的 undefined symbol

c - C 中整数列表加整数的结果是什么?

c - 我可以运行这个程序多少次

c++ - gtkmm,如何设置工具栏?