输入一些特殊数字时,"i"的值比应有的值少 1
When entering some special numbers,the value of "i" is one less than what it should be
我想解决这样一个问题:
从键盘输入指定的金额(以人民币为单位,如345.78(,然后显示支付金额的各种面额的人民币金额,并要求显示100元、50元、10元、5元、2元、1元、5个角度、1分、5分、1分。如345.78=100*3+10*4+5*1+0.5*1+0.1*2+0.01*8
以下是代码:
#include<stdio.h>
int main()
{int a1=0,a2=0,a3=0,a4=0,a5=0,a6=0,a7=0,a8=0,a9=0;
float m;
printf("enter money:");
scanf("%f",&m);
while(m>100.0)
{m=m-100;
a1++;}
while(m>50.0)
{m=m-50;
a2++;}
while(m>10.0)
{m=m-10;
a3++;}
while(m>5.0)
{m=m-5;
a4++;}
while(m>2.0)
{m=m-2;
a5++;}
while(m>1.0)
{m=m-1;
a6++;}
while(m>0.1)
{m=m-0.1;
a7++;}
while(m>0.05)
{m=m-0.05;
a8++;}
while(m>0.01)
{m=m-0.01;
a9++;}
printf("a1=%d,a2=%d,a3=%d,a4=%d,a5=%d,a6=%d,a7=%d,a8=%d,a9=%dn",a1,a2,a3,a4,a5,a6,a7,a8,a9);
return 0;
}
#include<stdio.h>
int main()
{
double n,r[8];
int k;
scanf("n=%lf",&n);
int a=n/100;
r[0]=n-a*100;
int b=r[0]/50;
r[1]=r[0]-b*50;
int c=r[1]/10;
r[2]=r[1]-c*10;
int d=r[2]/5;
r[3]=r[2]-d*5;
int e=r[3]/2;
r[4]=r[3]-e*2;
int f=r[4];
r[5]=r[4]-f*1;
int g=r[5]*10.00;
r[6]=r[5]-g*0.1;
int h=r[6]*20.00;
r[7]=r[6]-h*0.05;
int i=r[7]*100.00;
printf("%dn",a);
printf("%dn",b);
printf("%dn",c);
printf("%dn",d);
printf("%dn",e);
printf("%dn",f);
printf("%dn",g);
printf("%dn",h);
printf("%dn",i);
return 0;
}
然而,当输入0.78、0.98、0.99等数字时,值i
总是少一个。
这是怎么发生的?
您应该避免浮点运算。将输入读取为浮点,并将最小单位数存储为整数:
#include <iostream>
int main()
{
double input;
std::cin >> input;
int money = input * 100;
for (auto n : {10000, 5000, 1000, 500, 200, 100, 10, 5, 1}) {
std::cout << n / 100.0 << ":t" << money / n << 'n';
money %= n;
}
return 0;
}
输入:
1288.56
输出:
100: 12
50: 1
10: 3
5: 1
2: 1
1: 1
0.1: 5
0.05: 1
0.01: 1
相关文章:
- 从C++中的数字输入动态创建矩阵
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 非数字输入检查
- C++和 XAML - 来自文本框的数字输入
- 该代码不会在其中显示任何数字输入.如何使它显示任何输入
- 如何从数字输入文件中查找最大数字
- C++ 将数字输入数组并输出
- 无法从字符串获取数字输入
- 输入数字输入到if语句中
- C++数字输入的输入验证
- 来自单个数字输入的Arduino读取脉冲宽度频率和占空比
- 如何区分数字输入和字母输入
- 为什么我的程序取消了更多的数字输入
- C++:运行程序时出现分段错误(将文件中的数字输入数组)
- C++:使用for循环允许用户将数字输入到数组中
- C++ - 如何将空格分隔的数字输入数组
- _wtoi返回零:输入零或非数字输入
- 数字输入的输入验证
- 为什么我随机生成的数字输入都是零
- 我需要让一个数字输入的用户输出单个数字使用c++