【问题标题】:Error: invalid operands to binary expression ('float' and 'float')错误:二进制表达式的操作数无效('float' 和 'float')
【发布时间】:2016-09-24 03:07:43
【问题描述】:

如果之前有人问过这个问题,我深表歉意。我环顾四周,找不到解决方案,我是 C 新手。 我知道我无法从浮点数中获得 %。如果我使用 2 个浮点数,我如何能够捕捉到这个数学的其余部分?

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

/*
** Always use the largest coin possible
** keep track of coins used
** Print the final amount of coins
*/

int main (void)
{
  float change;
  int counter = 0;
  int division;
  //float rem;
  float quarter = 0.25;
  //float quarter = 0.25, dime = 0.10, nickel = 0.05, penny = 0.01;
  /* Prompt user for an amont of change*/
  do{
    printf("How much do we owe you in change? ");
    change = GetFloat();
  }
  while (change <= 0);
  if (change >= quarter)
  {
    division  = (change / quarter);
    counter += division;
    //change = (int)(change % quarter);
    printf("change: %.2f\n", change);
    printf("counter: %d\n ", counter);
  }

  return (0);
}

【问题讨论】:

    标签: c module floating-point cs50


    【解决方案1】:

    您可能需要检查 fmod.

    你也可以做类似change = change - (int)(change / quarter) * quarter

    【讨论】:

    • 谢谢加里,成功了,我还根据你的建议检查了 fmod,这个 change = fmod(change, Quarter);也将工作!再次感谢。
    【解决方案2】:

    您可以自己实现模数:

    https://en.wikipedia.org/wiki/Modulo_operation

    int a = (int)(change / quarter);
    int mod = (int)(change - (quarter * a));
    

    也可以这样做:

    long mod = ((long)(change * 1000) % (long)(quater * 1000));
    

    根据浮点数的精度修改 1000 并考虑将结果除以 1000!

    但也许最好重新考虑一下你真正想要的结果是什么?

    【讨论】:

      【解决方案3】:

      只需将所有变量放大 100,然后使用整数而不是浮点数。

      #include <cs50.h>
      #include <stdio.h>
      #include <ctype.h>
      #include <math.h>
      
      /*
      ** Always use the largest coin possible
      ** keep track of coins used
      ** Print the final amount of coins
      */
      
      int main (void)
      {
          float change_f;
          int change;
          int counter = 0;
          int division;
          //float rem;
          int quarter = 25;
          //int quarter = 25, dime = 10, nickel = 5, penny = 1;
          /* Prompt user for an amont of change*/
          do{
              printf("How much do we owe you in change? ");
              change_f = GetFloat();
          }
          while (change_f <= 0);
          change = (int)(change_f*100);
          if (change >= quarter)
          {
              division  = (change / quarter);
              counter += division;
              //change = (int)(change % quarter);
              printf("change: %.2f\n", change_f);
              printf("counter: %d\n ", counter);
          }
      
          return (0);
      }
      

      注意:根据输入精度选择比例因子,即如果是 3 位十进制数字,则选择 1000,依此类推。

      【讨论】:

        猜你喜欢
        • 2012-04-16
        • 2017-07-06
        • 1970-01-01
        • 1970-01-01
        • 2019-03-02
        • 2016-01-06
        • 1970-01-01
        • 2023-01-26
        相关资源
        最近更新 更多