2017-03-04 46 views
0

編譯此代碼時出現錯誤。 Z是爲了使用最少數量的硬幣而進行更改所需的最終硬幣數量。我在頂部附近定義了int Z = 0。我試過再次添加,並在打印語句中將類型更改爲f,但沒有運氣。CS50 PSET1貪婪 - 賦值錯誤和使用模(C)

這裏的錯誤:

error: format specifies type 'int' but the argument has type '<dependent type>' [-Werror,-Wformat] 
greedy.c:77:16: error: use of undeclared identifier 'z' 
printf("%i\n", z); 

這裏是我的代碼。我是初學者,所以任何建議或更正將受到歡迎。

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

int main(void) 
{ 
    //prompt user for amount of change owed 

    float f; 
    int num; //amount of change 

    do 
    { 
     printf("O hai! How much change is owed?:\n"); 
     f = get_float(); 
    } 
    while (f < 0); //verify input is positive 

    num = round(f * 100); //rounds float 

    //commence making change 

    do{ 

     int c, e, i, j; 

     int z = 0; //z = coins 

     if (num % 25 == 0) // verifies that num is divisible by 25 so only 25c coins necessary 
     { 
      z = (num/25) + z; // updates final number of 25c coins 
     } 
     else if (num % 25 > 0) 
     { 

      i = num/25; 
      j = num % 25; 

     } 

     else if ((num/25 < 0) || (num >=10 && num < 25)) //this means that f is less than 25 cents so has to be divided by 10 cent coins 
     { 

      num = c; 
      c = j + c; //add remainder of num to the number to start with 
     } 

     if (c % 10 == 0) // c is less than 25c but divisible by 10c pieces 
     { 
      z = (c/10) + z; //d is the final number of 10c coins 

     } 

     else if (c /10 < 1) //this means it's less than 10c 
     { 
      c = e; // Then c must be less than 10c 
     } 

     else if (e % 5 == 0) // divisible by 5c pieces 
     { 
      z = (e/5) + z; // g is the number of 5 cent pieces 

     } 

     else if (e % 5 < 0) 
     { 
     z = (e/1) + z; //h is the number of pennies   
     } 

    } 
    while (num > 0); //num is rounded float 

    printf("%i\n", z); 
} 

回答

1

首先,我建議你應該用縮進適當地格式化你的代碼。

然後,錯誤的原因是z在與do循環關聯的塊中聲明,並且printf("%i\n", z);超出其範圍。 要擺脫此錯誤,請在printf()調用處可見的位置聲明z - 例如,在do循環之前。

需要注意的是,宣佈int Z = 0不會起作用,因爲標識的名稱是區分大小寫的C.

0

就像已經說了,你是裏面的do-while循環,所以它是可見只在循環裏聲明ž。

你應該在循環開始之前聲明它,所以你也可以在循環結束後使用它。像這樣:

int z = 0; //z = coins 
do{ 
***YOUR CODE*** 
} while();