任何人都可以帮我处理我的代码
int main(void){
int money, x[6],i[6];
x[0] = 1000; x[1] = 500; x[2] = 200; x[3] = 100; x[4] = 50; x[5] = 20;
printf("Enter your Money: ");
scanf("%d", &money);
printf("\nBreakdown:\n");
for(int y=0;money != 0; y++){
i[y] = ( money - (money % x[y]) )/x[y];
money = (money % x[y]);
printf("%10d x %d = %5d \n", x[y], i[y], (x[y] * i[y]));
}
printf("---------------------------\n");
printf("Total:");
printf(" %d", money);
的getch();
}
如何检查是否有余数&它会说输入无效
答案 0 :(得分:0)
这是一个适用于所有输入的版本,而不仅仅是可被20整除的版本。
int main(void){
int money, money2, x[7],i[7], y;
x[0] = 1000; x[1] = 500; x[2] = 200; x[3] = 100; x[4] = 50; x[5] = 20, x[6] = 1;
printf("Enter your Money: ");
scanf("%d", &money);
money2 = money;
printf("\nBreakdown:\n");
for(y=0;money >0; y++){
i[y] = ( money - (money % x[y]) )/x[y];
money = (money % x[y]);
printf("%10d x %d = %5d \n", x[y], i[y], (x[y] * i[y]));
}
printf("---------------------------\n");
printf("Total:");
printf(" %d", money2);
getch();
}
所做的更改
数组大小增加到7.并添加x[6] = 1
。这确保了最终案例的处理。
添加了一个额外的变量money2
来存储最后用于打印的总金额。在您的代码中,money
变量在到达打印函数时会更改并且值为零。
答案 1 :(得分:0)
你可以为x [6] = 5,x [7] = 2,x [8] = 1等数组添加更多值,我认为这是最好的想法。
这样你就可以计算出5,2和1的倍数
否则
int nTemp = money; //Take a temp variable to store total money
for(int y=0;money != 0 && y<6; y++){ // check both money!=0 and y should be less than 6
i[y] = ( money - (money % x[y]) )/x[y];
money = (money % x[y]);
printf("%10d x %d = %5d \n", x[y], i[y], (x[y] * i[y]));
}
if(money>0) // if remainder is there you can print
printf("Remaining change = %d\n", money);
printf("---------------------------\n");
printf("Total:");
printf(" %d", nTemp); // print nTemp here, i.e total money