繁体   English   中英

C-While循环中的If语句。 连续Scanf()

[英]C - If statement inside While loop. Continuous Scanf()

好吧,我希望该功能将更改返回给我。 而且我有限制,我无法插入所有类型的硬币。 例如,如果我有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€\n\n");

float str = 0 ;
float count = 0 ;
while(count <= price){

  printf("Insert coins\n" );
  scanf("%f\n",&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表示,但永远不能将其精确地表示为小数部分。 因此,您的比较==可能会很难。 就像(在我们的十进制系统中) 1.0 / 3.0 == 0.3333永远不会为真,无论您在十进制中添加多少个3。

代替比较绝对值,您应该重新检查输入的值是否足够接近目标值,如下所示:

...

float abs(float a) {return (a < 0) ? -a : a; }

const float epsilon = 0.005;

...

  printf("Insert coins\n" );
  scanf("%f",&str );

  if(abs(str - 0.05) < epsilon) {
      printf("Gave 0.05\n");
    count = count + 0.05;
  }

  if(abs(str - 0.10) < epsilon) {
      printf("Gave 0.10\n");
     count = count + 0.10;
  }

  ...

但是,对于您的问题,将值读为字符串可能会更容易(且可拆分),然后可以使用strcmp将其与期望值进行比较,并对其进行适当处理,如下所示:

 char  input[100];

 ...

 scanf("%100s", input);
 input[99] = '\0';

 if(0 == strcmp(input, "0.05")) {
    printf("You gave 0.05\n");
    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€\n\n");

    char input[100] = {0};
    float  count = 0 ;
    while(count <= price){

        printf("Insert coins\n" );
        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 %s\n", input_map[i].input);
                count += input_map[i].value;
                break;
            }

        }

    }

    return count - price;
}


int main(int argc, char** argv) {

    printf("Your change %f\n", givemeChange(0.5));

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM