2016-09-28 65 views
-1
#include <stdio.h> 
#include <math.h> 
#include <cs50.h> 

int main(void) 
{ 
    float x; 
    printf("O hai! How much change is owed?\n"); 
    do 
    { 
     x = GetFloat(); 
     x = x * 100; 
     return roundf(x); 
     int c = 0; 
     do 
     { 
      return x = x - 25; 
      return c = c + 1; 
     } 
     while (x >= 25); 
     printf("%d coins\n", c); 
    } 
    while (x <= 0); 
} 

当我输入一个像.60这样的浮点数时,它应该将其转换为一个整数,然后检测它是否更大这将是第一次在硬币从四分之一到一角硬币减少到镍等的过程中,但当我第一次尝试打印出第一个序列完成后得到的值时,它没有返回任何东西。我想创建一个贪婪的算法,但我的代码不会返回一个值在结尾

+6

该代码中有三个太多的return语句。 – WhozCraig

回答

5

只要程序命中return roundf(x);它就会停止(因为main已经返回),这就是为什么它在读取第一个数字后没有输出。

+0

如何在不显示错误消息的情况下移除roundf(x)上的返回:忽略使用const属性声明的函数的返回值[-Werror,-Wunused-value] roundf(x); –

+0

你根本不应该回来;请参阅@cdlane的答案。 –

1

此代码只需要一个return声明,但它是您忘记的声明。其他语法错误,所以你会想要检查return实际上是什么。你的代码有你需要的大部分,但不是按正确的顺序。下面的返工确实代码在这一点上做了什么,并暗示下一步该去哪里:

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

int main(void) 
{ 
    printf("O hai! How much change is owed?\n"); 

    float x = GetFloat(); 
    x = x * 100; 
    x = roundf(x); 

    int coins[] = { 25 }; 

    int coin = 0; 

    do 
    { 
     int c = 0; 

     while (x >= coins[coin]) 
     { 
      x = x - coins[coin]; 
      c = c + 1; 
     } 

     printf("%d coins worth %d\n", c, coins[coin]); 
    } 
    while (--coin >= 0); 

    return 0; 
} 

I.e.您需要扩大数组coins以包含其他面额并将coin变量设置为coins中最大硬币的索引。每次通过循环时,更改coin以索引下一个最大的硬币,直到没有更多。

我改变了你的内心do { ... } while()为一个简单的while() { ... }循环,因为你不能假定一个硬币将需要进行更改。

相关问题