私はCの新機能です。私はPythonの背景から来ています。私は自分のコードでどこが間違っていたのか知りたい。Cを学ぶには、 "欲張りな" CS50の解決策が必要です
私はcs50貪欲の問題を抱えています。私のコードで何が間違っていますか?それはいくつかの数字で動作しますが、他は動作しません。私はどのくらいの変更を返すようにユーザーからの入力を取得しようとしている$ 0.25、$ 10、$ .05、$ .01
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float n;
do
{
n = get_float("How much change is owed?\n");
}
while(n == EOF);
int minimumamountofcoins = 0;
if (n/.25 >=1){
do
{
n -= .25;
minimumamountofcoins++;
}
while (n/.25 >= 1);
}
if (n/.1 >=1){
do
{
n -= .1;
minimumamountofcoins++;
}
while (n/.1 >=1);
}
if(n/.05 >=1){
do
{
n -= .05;
minimumamountofcoins++;
}
while (n/.05 >=1);
}
if (n/.01 >=1){
do
{
n -= .01;
minimumamountofcoins++;
}
while (n/.01 >=1);
}
printf("The minimum amount of coins is %d\n", minimumamountofcoins);
}
を使用して返すことができるコインの最小数を計算する
新しいコード:(4.2を入力するとき以外は完璧に動作します)
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float n;
do
{
n = get_float("How much change is owed?\n");
}
while(n == EOF);
int cents = (int)(n * 100);
int minimumamountofcoins = 0;
if (cents/25 >= 1){
while (cents/25 >= 1)
{
cents -= 25;
minimumamountofcoins++;
}
}
if (cents/10 >= 1){
while (cents/10 >= 1)
{
cents -= 10;
minimumamountofcoins++;
}
}
if(cents/5 >= 1){
while (cents/5 >= 1)
{
cents -= 5;
minimumamountofcoins++;
}
}
if (cents/1 >= 1){
while (cents/1 >= 1)
{
cents -= 1;
minimumamountofcoins++;
}
}
printf("The minimum amount of coins is %d\n", minimumamountofcoins);
}
はなぜあなたのコードが動作しないため、入力の例を与えない:
したがって、コードは次のようになりますか?その入力については、あなたが期待する出力とプログラムが返すものを言います。 –
"変更"の質問を調査してください。アドバイスは、整数とセントで作業することです。 [浮動小数点数の計算は壊れていますか?](0120-13-0111) –
いくつかの提案:整数を使用します(ペニーですべての金額を使用します)最後の.01 whileループが必要です(残量*はペニーの数です)。 "count"という単語全体を "amount"に置き換えてください。 – jarmod