gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:59:42 27 4
gpt4 key购买 nike

编译此代码时出现错误。 Z 是找零所需的最终硬币数量,目标是使用最少数量的硬币。我在顶部附近定义了int Z = 0。我尝试再次添加 int z 并将 print 语句中的类型更改为 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);
}

最佳答案

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

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

请注意,声明 int Z = 0 不起作用,因为标识符的名称在 C 中区分大小写。

关于CS50 PSET1 贪婪 - 分配错误并使用模 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42598391/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com