2015-09-06 58 views
1

我的代碼旨在顯示一個人需要一定金額的硬幣的最少數量。我將這個值轉換成分,然後用循環來測試每一個不同的硬幣。您可能會看到printf中用於測試目的的變量,以查看它出錯的位置。這些循環會一直持續下去,不會像循環重複一樣多次減去C的值。恩。 c-25保持在475美分,而不是每次循環重複25次(價值$ 5.00)。爲什麼我的程序中的循環沒有終止?

#include <stdio.h> 
#include <cs50.h> 
#include <math.h> 

int main(void) 
{ 
float c=0; 
int i=0; 
int y=0; 

    printf("How much change do you owe?\n"); 
    c=GetFloat(); 
    c=c*100; 
    printf("%f\n", c); 
    do 
    { 
     c-25; 
     printf("%d\n", c-25); 
     if (c>25) 
     { 
      i++; 
      printf("%d\n", i); 
     } 
    } 
     while (c>=25); 
    printf("%d\n", i); 

    do 
    { 
     y=c-10; 
     if (y>0) 
     { 
      i++; 
     } 
    } 
     while (y>10); 
    if (y<=10) 
    { 
     printf("%d\n", i); 
    } 
    do 
    { 
     y=c-5; 
     if (y>0) 
     { 
      i++; 
     } 
    } 
     while (y>5); 
    if (y<=5) 
    { 
     printf("%d\n", i); 
    } 
    do 
    { 
     y=c-1; 
     if (y>0) 
     { 
      i++; 
     } 
    } 
     while (y>1); 
    if (y==0) 
    { 
     printf("%d\n", i); 
    } 
} 

注:這是 「時代變革」 方案,CS50

+0

**如果您需要確切值,請勿使用'float'!** – Olaf

回答

4

c是從來沒有改變過。

有該聲明沒有影響:

c-25; 

這或許應該是:

c = c - 25; 

c -= 25; 
1

這裏是你的代碼中的一些言論:

#include <stdio.h> 
#include <cs50.h> 
#include <math.h> 

int main(void){ 
// use self-explanatory and meaningful names of your variables 
float c = 0; 
int i = 0; 
int y = 0; 

// input 
printf("How much change do you owe?\n"); 
c = GetFloat(); 
c = c * 100; 
// print input 
printf("%f\n", c); 

// add comment explaining the purpose of this loop 
do{ 
    c = c - 25; // corrected to decrement by 25 

    printf("%d\n", c); 
    if (c > 25){ 
     i++; 
     printf("%d\n", i); 
    } 
}while(c >= 25); 

printf("%d\n", i); 

// add comment explaining the purpose of this loop 
do{ 
    y = c - 10; 
    if (y > 0){ 
     i++; 
    } 
}while(y > 10); 

// add comment explaining the purpose of this condition statement 
if (y <= 10){ 
    printf("%d\n", i); 
} 

// add comment explaining the purpose of this loop 
do{ 
    y = c-5; 
    if (y > 0){ 
     i++; 
    } 
}while(y > 5); 

// add comment explaining the purpose of this condition statement 
if (y <= 5){ 
    printf("%d\n", i); 
} 

// add comment explaining the purpose of this condition statement 
do{ 
    y = c-1; 
    if (y > 0){ 
     i++; 
    } 
}while(y > 1); 
// add comment explaining the purpose of this condition statement 
if(y == 0){ 
    printf("%d\n", i); 
} 
} 

主要問題來自終止條件計數器變量增量/減量,這是錯誤或丟失,並導致無限循環。

相關問題