我刚刚参加了CS50课程,正在与Pset 1作斗争。这是我的代码:
#include <cs50.h>
#include <stdio.h>
int get_cents(void);
int calculate_quarters(int cents);
int calculate_dimes(int cents);
int calculate_nickels(int cents);
int calculate_pennies(int cents);
int main(void)
{
// Ask how many cents the customer is owed
int cents = get_cents();
// Calculate the number of quarters to give the customer
int quarters = calculate_quarters(cents);
cents = cents - quarters * 25;
// Calculate the number of dimes to give the customer
int dimes = calculate_dimes(cents);
cents = cents - dimes * 10;
// Calculate the number of nickels to give the customer
int nickels = calculate_nickels(cents);
cents = cents - nickels * 5;
// Calculate the number of pennies to give the customer
int pennies = calculate_pennies(cents);
cents = cents - pennies * 1;
// Sum coins
int coins = quarters + dimes + nickels + pennies;
// Print total number of coins to give the customer
printf("%in", quarters);
}
int get_cents(void)
{
int owed;
do
{
owed = get_int("Change owed: ");
} while (owed<=0);
return owed;
}
int calculate_quarters(int cents)
{
int n;
while (cents <= 25)
{
n++;
cents = cents - 25;
}
return n;
}
int calculate_dimes(int cents)
{
int n;
while (cents <= 10)
{
n++;
cents = cents - 10;
}
return n;
}
int calculate_nickels(int cents)
{
int n;
while (cents <= 5)
{
n++;
cents = cents - 5;
}
return n;
}
int calculate_pennies(int cents)
{
int n;
while (cents <= 1)
{
n++;
cents = cents - 1;
}
return n;
}
该代码返回大量类似于";277258257";。问题出在函数上,但我不知道它是什么。当我在主函数中使用相同的while循环而不是创建函数时,它可以完美地工作(但它不符合练习要求,因为CS50机器人也会检查代码中是否存在这些函数(。
对不起我的英语,我的主要语言是法语,有时我会说一些奇怪的话。如果我说的任何话都没有意义,请告诉我。
在以下中
int n;
/* ... */
n++
n
未初始化,包含一个不确定的值。有时被称为垃圾值,该值实际上是随机的。在n++
中使用此值会调用Undefined Behavior。
初始化每个变量。
int n = 0;
用于计算硬币的每个while
循环都使用了错误的运算符。更改
while (cents <= 25)
至
while (cents >= 25)
其他人也是如此。
coins
未使用。更改
printf("%in", quarters);
至
printf("%in", coins);