C – 舍入问题(CS50)

我已经谷歌搜索了好几天,我迷路了。 所以在网上做CS50似乎无法掌握这一轮数字。 我的程序搞乱了像2.10这样的浮点数乘以100这样的整数输出209.xxxxxxxx

就像我说我已经阅读了无数的post,我应该使用ceilf并包含 但是我收到了一个错误

greedy.c :(。text + 0x74):未定义引用`ceilf’collect2:错误:ld返回1退出状态make:*** [greedy]错误1 adam @ beethoven:〜/ projects / atom / edx / pSet1 /贪婪$

我已经看过关于-lm和某个文件的post,但如果我说实话,我不明白这意味着什么。

我绝不是在寻找一个彻底的解决方案,只是在改进方面提供指导。

这是我的代码,可能不像某些人希望的那样精简,但我回到这里的基础;)

#include  #include  int main() { // Initialize Variables int coinsTotal = 0, quarter = 25, dime = 10, nickel = 5, penny = 1, cents; float changeDue; do { printf("How much change are you owed? (Format = 0.00)($): "); scanf("%f", &changeDue ); // Convert to cents cents = changeDue * 100; } while(cents = quarter) { cents = cents - quarter; coinsTotal = coinsTotal + 1; } if (cents == 0) { printf("The miminum number of coins is: %d\n", coinsTotal); } else { while (cents >= dime) { cents - dime; coinsTotal = coinsTotal + 1; } if (cents == 0) { printf("The minimum number of coins is: %d\n", coinsTotal); } else { while (cents >= nickel) { cents = cents - nickel; coinsTotal = coinsTotal + 1; } if (cents == 0) { printf("The minimum number of coins is: %d\n", coinsTotal); } else { while (cents >= penny) { cents = cents - penny; coinsTotal = coinsTotal + 1; } if (cents == 0) { printf("The minimum number of coins is: %d\n", coinsTotal); } } } } } 

基本上它应该计算出给定金额所需的最少数量的硬币。 它适用于大多数情况,直到浮子陷入困境。 请原谅我喜欢写的东西,所以我学得更好。

更新尝试使用-lm使用GCC进行编译但仍然失败。 adam @ beethoven:〜/ projects / atom / edx / pSet1 / greedy $ gcc -o foo -lm greedy.c /tmp/cc3qHAK7.o:in function main': greedy.c:(.text+0x6e): undefined reference to ceilf’collection2:错误:ld返回1退出状态adam @ beethoven:〜/ projects / atom / edx / pSet1 / greedy $

解决方案而不是使用make命令我使用了gcc并添加了-lm标志在命令结尾处 gcc -o foo greedy.c -lm

我已经看过关于-lm和某个文件的post,但如果我说实话,我不明白这意味着什么。

您必须链接到数学库才能修复错误。 数学函数实现通常作为单独的库(数学库)放置。 如果对链接器命令使用gcc add -lm

我认为你想要将浮点数舍入到最接近的整数。 ceilf没有这样做,它正在ceilf 。 您可以使用此宏在可能的情况下舍入到最近的长度:

 #define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5)) 

此外,您收到链接错误,因为您没有链接数学库。 例如使用:

 gcc greedy.c -lm -o greedy