错误:二进制表达式的操作数无效('浮动'浮动')

时间:2016-05-26 08:20:23

标签: c module floating-point cs50

如果之前已经提出这个问题,我道歉。我环顾四周,无法找到解决方案,我是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);
}

3 个答案:

答案 0 :(得分:5)

您可能需要查看 fmod

您还可以执行change = change - (int)(change / quarter) * quarter

之类的操作

答案 1 :(得分: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!

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

答案 2 :(得分:0)

将所有变量放大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,依此类推。