該代碼有效,但很奇怪,當我運行它并給出數量 375 時,結果如下:
數量: 375 2個音符 100個 2個音符 50個 2個音符 20個 2個音符 10個 2個音符 5個 2個音符 2個 1個音符
它應該給我 3 個 100 的注釋,一個 50 的注釋,一個 20 的注釋和一個 5 的注釋。我對編碼真的很陌生,所以這可能真的很容易。
int main(void)
{
int quantity = get_int("Quantity: ");
int hundred = 0;
int fifty = 0;
int twenty = 0;
int ten = 0;
int five = 0;
int two = 0;
int one = 0;
while ( quantity > 0 )
{
if ( quantity >= 100 )
{
quantity -= 100;
hundred ;
}
if ( quantity >= 50 )
{
quantity -= 50;
fifty ;
}
if ( quantity >= 20 )
{
quantity -= 20;
twenty ;
}
if ( quantity >= 10 )
{
quantity -= 10;
ten ;
}
if ( quantity >= 5)
{
quantity -= 5;
five ;
}
if ( quantity >= 2)
{
quantity -= 2;
two ;
}
if ( quantity >= 1 )
{
quantity -= 1;
one ;
}
}
printf("%d notes of 100\n", hundred);
printf("%d notes of 50\n", fifty);
printf("%d notes of 20\n", twenty);
printf("%d notes of 10\n", ten);
printf("%d notes of 5\n", five);
printf("%d notes of 2\n", two);
printf("%d notes of 1\n", one);
uj5u.com熱心網友回復:
好吧,沒有謊言,這樣做很丑陋,但好吧..如果它有效:)這里是你可以這樣做的方法:
int main(void)
{
int quantity;
scanf("%d", &quantity);
int hundred = 0;
int fifty = 0;
int twenty = 0;
int ten = 0;
int five = 0;
int two = 0;
int one = 0;
while ( quantity >= 100 )
{
quantity -= 100;
hundred ;
}
while ( quantity >= 50 )
{
quantity -= 50;
fifty ;
}
while ( quantity >= 20 )
{
quantity -= 20;
twenty ;
}
while ( quantity >= 10 )
{
quantity -= 10;
ten ;
}
while ( quantity >= 5)
{
quantity -= 5;
five ;
}
while ( quantity >= 2)
{
quantity -= 2;
two ;
}
while ( quantity >= 1 )
{
quantity -= 1;
one ;
}
printf("%d notes of 100\n", hundred);
printf("%d notes of 50\n", fifty);
printf("%d notes of 20\n", twenty);
printf("%d notes of 10\n", ten);
printf("%d notes of 5\n", five);
printf("%d notes of 2\n", two);
printf("%d notes of 1\n", one);
}
uj5u.com熱心網友回復:
您正在檢查是否可以洗掉 100,然后檢查是否可以洗掉 50,等等,然后重新開始。那不正確。
你想減去 100 秒,直到你不能。只有 THEN 你想減去 50s 直到你不能。
while ( quantity >= 100 ) { quantity -= 100; hundred ; }
while ( quantity >= 50 ) { quantity -= 50; fifty ; }
...
實作相同目的的更好方法是使用模數。
hundred = quantity / 100; quantity = quantity % 100;
fifty = quantity / 50; quantity = quantity % 50;
...
下一步是使用值陣列。
int bills[] = { 100, 50, ... };
const size_t NUM_BILLS = sizeof(bills) / sizeof(bills[0]);
int counts[NUM_BILLS] = { 0 };
但是編碼這個版本是留給你的:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366248.html
標籤:C
