C - While 循环中的 if 语句.连续扫描()



好吧,我希望这个函数向我返回更改。而且我有限制,我不能插入所有类型的硬币。例如,如果我有givemeChange(0.50)我想插入钱,直到它们足以支付产品。我找不到解决方案。我在终端中插入 2 个数字,然后该功能始终return 0.69

这是我的代码:

谢谢你的时间

float givemeChange(float price){
printf("Only these coins are allowed:n" );
printf("0.05€ 0.10€ 0.20€ 0.50€ 1€ 2€nn");
float str = 0 ;
float count = 0 ;
while(count <= price){
printf("Insert coinsn" );
scanf("%fn",&str );
if(str == 0.05){
count = count + 0.05;
}
if(str == 0.10){
count = count + 0.10;
}
if(str == 0.20){
count = count + 0.20;
}
if(str == 0.50){
count = count + 0.50;
}
if(str == 1){
count = count + 1;
}
if(str == 2){
count = count + 2;
}
else{
return 0.69;
}
}
return (price-count);
}

我猜你在比较时遇到了麻烦: 在二进制系统中,对于分数,只能精确表示 2 的幂 -0.2不能在二进制系统中精确表示,因为在二进制系统中,它可能是一个永无止境的分数。 你在十进制中遇到像1/3这样的分数,它大致0.33表示,但你永远不能完全用十进制分数来表示它。因此,您可能很难进行比较==。就像(在我们的十进制系统中(无论您在小数点处添加多少 3,1.0 / 3.0 == 0.3333永远不会是真的。

与其比较绝对值,不如回过头来检查输入的值是否足够接近目标值,如下所示:

...
float abs(float a) {return (a < 0) ? -a : a; }
const float epsilon = 0.005;
...
printf("Insert coinsn" );
scanf("%f",&str );
if(abs(str - 0.05) < epsilon) {
printf("Gave 0.05n");
count = count + 0.05;
}
if(abs(str - 0.10) < epsilon) {
printf("Gave 0.10n");
count = count + 0.10;
}
...

但是,对于您的问题,将值作为字符串读取可能更容易(并且可行(,然后您可以使用strcmp将它们与预期值进行比较并适当地处理它们,如下所示:

char  input[100];
...
scanf("%100s", input);
input[99] = '';
if(0 == strcmp(input, "0.05")) {
printf("You gave 0.05n");
count += 0.05;
}
/* and so on with the other options */

如果您还想接受.5等输入,则必须编写自己的比较函数。

解决方案由您选择,只是为了完整性,这里有一个可以立即编译的紧凑解决方案 - 带有一种查找表,以防止所有那些if's键入...:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
float givemeChange(float price){
struct {const char* input; float value;} input_map[] =
{
{"0.05", 0.05},
{"0.10", 0.10},
{"0.20", 0.20},
{"0.50", 0.5}
};
printf("Only these coins are allowed:n" );
printf("0.05€ 0.10€ 0.20€ 0.50€ 1€ 2€nn");
char input[100] = {0};
float  count = 0 ;
while(count <= price){
printf("Insert coinsn" );
scanf("%100s",input );
input[99] = 0;
for(size_t i = 0; i < sizeof(input_map) / sizeof(input_map[0]); ++i) {
if(0 == strcmp(input_map[i].input, input)) {
printf("Gave %sn", input_map[i].input);
count += input_map[i].value;
break;
}
}
}
return count - price;
}

int main(int argc, char** argv) {
printf("Your change %fn", givemeChange(0.5));
}

最新更新