CS50 PSET1贪婪 - 分配错误并使用模数(C)

时间:2017-03-04 16:32:00

标签: c cs50

编译此代码时出错。 Z是进行更改所需的硬币的最终计数,目的是使用最少数量的硬币。我在顶部附近定义了int Z = 0。我已尝试再次添加int z并在打印语句中将类型更改为f,但没有运气。

这是错误:

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);
}

2 个答案:

答案 0 :(得分:1)

首先,我建议您应该使用缩进来正确格式化代码。

然后,错误的原因是z在与do循环相关联的块内声明,printf("%i\n", z);超出其范围。 要摆脱此错误,请在z调用可见的位置声明printf() - 例如,在do循环之前。

请注意,声明int Z = 0无法正常工作,因为标识符&#39;名称在C中区分大小写。

答案 1 :(得分:0)

就像已经说过的那样,你在do-while循环中声明了z,所以它只在循环内部可见。

你应该在循环开始之前声明它,所以你也可以在循环结束后使用它。像这样:

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