更新时间:2021-10-06 00:00:38
关于代码:
cents
时, code> amount_left ,在第一个循环中,如果需要多次迭代,则结果将是不正确的。 amount_left-10> = 0
更改为 amount_left> = 10
。 printf
语句最有可能(按文字显示)用于打印通过提供的金额获得的硬币数量。cents
when there would be amount_left
, in the case of the first loop if it require more that one iteration, the result would be incorrect.amount_left - 10 >= 0
by amount_left >= 10
.printf
statement most probably (by the text) is for printing the count of coin gained by the amount provided.代码:
#include <stdio.h>
#include <math.h>
int main(void) {
float amount = 0;
int cents = 0;
int count = 0;
int amount_left = 0;
amount = .30;
cents = (int)round(amount * 100);
printf("%d\n", cents);
amount_left = cents;
while (amount_left >= 25) {
count++;
amount_left -= 25;
}
while (amount_left >= 10) {
count++;
amount_left -= 10;
}
while (amount_left >= 5) {
count++;
amount_left -= 5;
}
while (amount_left >= 1) {
count = count + 1;
amount_left -= 1;
}
printf("You get %d coins\n", count);
}
使用公式: initial_amount
= 硬币价值
* 已使用硬币
+ amount_left
Using the formula: initial_amount
= coin value
* coin used
+ amount_left
这可以用C写成:
initial_amount
/ 硬币价值
= 已使用硬币
初始金额
%硬币价值
= amount_left
initial_amount
/ coin value
= coin used
initial_amount
% coin value
= amount_left
更优化的解决方案:
#include <stdio.h>
#include <math.h>
int main(void) {
float amount = 0;
int cents = 0;
int count = 0;
int amount_left = 0;
amount = .30;
cents = (int)round(amount * 100);
printf("%d\n", cents);
amount_left = cents; // beginning with 30 cents
count += amount_left / 25; // 30 / 25 = 1, one 25 cent coin
amount_left %= 25; // 30 % 25 = 5, left with 5 cents
count += amount_left / 10; // 5 / 10 = 0 no coin used
amount_left %= 10; // 5 % 10 = 5 left the same 5 cents
count += amount_left / 5; // 5 / 5 = 1 one 5 cent coin
amount_left %= 5; // 5 % 5 = 0 left with 0 cents
count += amount_left; // not needed 1 cent coins.
printf("You get %d coins\n", count);
}
注意:
while循环
操作 17/5 = 3
用整数运算在 C
和 17%5 = 2
中。 N
的硬币,数量/ N
硬币计数(可以为0,例如: amount = 9
和 N = 10
, 9/10 = 0
),剩余的金额为金额%N
。 amount = 0
。while loop
operation 17 / 5 = 3
in integers arithmetic in C
and 17 % 5 = 2
.N
, amount / N
coins count (could be 0, eg: amount = 9
and N = 10
, 9/10 = 0
in integer division) and the amount left is amount % N
.amount = 0
.