Error invalid operands to binary have float and float

Below is my code: #include int main ( ) { float a = 5,b = 2; int c,d; c = a % b; d = a/2; printf("%dn",d); return 0; } When I try to c...

Below is my code:

#include <stdio.h>

int main ( )   
{
    float a = 5,b = 2;    
    int c,d;    
    c = a % b;
    d = a/2;    
    printf("%dn",d);    
    return 0;
}

When I try to compile this, I get

«Invalid operands to binary %»

on the 6th line. How do I solve this?

Sourav Ghosh's user avatar

Sourav Ghosh

132k16 gold badges184 silver badges258 bronze badges

asked Nov 17, 2015 at 13:36

Osama 's user avatar

0

 c = a % b;

You can’t use float as operand to % operator.

Use fmod from math.h instead .

double a=5,b=2,c;
c=fmod(a,b);                 // it returns double

answered Nov 17, 2015 at 13:41

ameyCU's user avatar

ameyCUameyCU

16.4k2 gold badges25 silver badges40 bronze badges

As others have already mentioned, you’re having issue with the type of the operands for modulo operator. You need to have the operands of type int for the modulo operator.

To add some reference, quoting C11 standard, chapter §6.5.5, Multiplicative operators

[..] The operands of the % operator shall
have integer type.

answered Nov 17, 2015 at 13:52

Sourav Ghosh's user avatar

Sourav GhoshSourav Ghosh

132k16 gold badges184 silver badges258 bronze badges

You can’t use modulo (%) for float args. Maybe you want to do:

c = (int) a % (int) b;

answered Nov 17, 2015 at 13:41

poko's user avatar

pokopoko

5752 silver badges8 bronze badges

Modulo operator % is for use with integers, you have used floats.

You could use fmod(a,b) and #include <cmath>.

answered Nov 17, 2015 at 13:41

Panda's user avatar

PandaPanda

1,23121 silver badges27 bronze badges

Are you sure it’s on the 6th line? It’s more likely to be the line that says

c = a % b;

because % only expects integer values, not floating point. You probably need to do a bit of casting if you really want a and b to be floats.

answered Nov 17, 2015 at 13:45

JonP's user avatar

JonPJonP

6175 silver badges13 bronze badges

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    float matrix[7][7]={{1.3,15.4,7.8,13.7,10.1,2.5,17.4},
                        {12.3,7.5,6.3,11.4,18.5,14.9,8.2},
                        {7.3,11.2,4.4,10.8,8.9,17.2,18.4},
                        {15.8,17.5,4.8,9.8,7.1,12.6,11.7},
                        {5.3,13.6,13.2,19.2,16.4,2.7,1.8},
                        {9.5,0.7,1.9,14.3,0.2,5.4,3.1},
                        {0.8,19.9,6.7,12.7,2.6,4.9,11.5}};
    float max=matrix[0][0];
    float min=matrix[0][0];
    float sclproizv;
    int imax,jmin;
    for(int i=0;i<7;i++){
        for(int j=0;j<7;j++){
            printf("%.1ft", matrix[i][j]);
            if(matrix[i][j]>max)
            {
                max=matrix[i][j];
                imax=i;
 
            }
            if(matrix[i][j]<min)
            {
                min=matrix[i][j];
                jmin=j;
            }
            sclproizv=matrix[imax,j]*matrix[i,jmin];
        }
        printf("n");
    }
    printf("Scalyarnoe proizvedenie:%.1fn", sclproizv);
    return 0;
}

If you are trying to run modulo / remainder operator like below, there are higher chances you might get an error as “error: invalid operands to binary” The solution for this error is as mentioned below.

 $ vim using_mod.c 
#include <stdio.h>

int main(void) {
        float num = 11.00;
        int remainder = num % 3.0;

        if (remainder == 0) {
                printf("number is divisiblen");
        } else {
                printf("number is not divisible: Remainder = %dn", remainder);
        }
        return 0;
}
 $ gcc using_mod.c 
using_mod.c: In function ‘main’:
using_mod.c:5:22: error: invalid operands to binary % (have ‘float’ and ‘double’)
  int remainder = num % 3.0; 

Solution :

The remainder operator (otherwise known as the modulo operator) % is a binary operator (i.e., takes exactly 2 operands) and operates only on integer types (e.g., short, int, long, long long, etc).

Hence, we either need to change float to int, or typecast both the values before and after % operator. like

int remainder = (int)num % (int)3.0;

The complete working program will look like as below,

 $ vim using_mod.c 
#include <stdio.h>

int main(void) {
        float num = 6.00;
        int remainder = (int)num % (int)3.0;

        if (remainder == 0) {
                printf("number is divisiblen");
        } else {
                printf("number is not divisible: Remainder = %dn", remainder);
        }
        return 0;
}

Post


Essentials Only

Full Version

chowam01

New Member

  • Total Posts : 1
  • Reward points : 0
  • Joined: 2020/11/18 16:10:52
  • Location: 0
  • Status: offline



2020/11/18 20:51:02

(permalink)

0

I am trying to cast float to bitwise int in C. Here’s my code snippet:
write_eeprom(INDEX_CONFIG_TEMPERATURE_OFFSET_HIGH_INT, (unsigned int) (temperature_offset>>16));
write_eeprom(INDEX_CONFIG_TEMPERATURE_OFFSET_LOW_INT, (unsigned int) (temperature_offset));

I am getting the following error:
error: invalid operands to binary >> (have ‘float’ and ‘int’),

while trying to compile. Here, temperature_offset is a float type and I am trying to cast it as high int and low int as I am trying to save data in EEPROM in 16-bit chunks (as I am using a 16-bit microcontroller). I know that the ‘>>’ does not apply to float types. How can I fix this issue? I tried using a separate unsigned int variable called temperature_offset_int and then I used memcpy to cast the float into it. However, my MPLAB IDE displays an error message ‘unexpected token’ when I use the following:

memcpy(&temperature_offset_int, &temperature_offset, sizeof temperature_offset);

Does anyone know a solution to this problem?

#1

pic24

ric

Super Member

  • Total Posts : 35931
  • Reward points : 0
  • Joined: 2003/11/07 12:41:26
  • Location: Australia, Melbourne
  • Status: offline

Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)


2020/11/18 22:59:18

(permalink)

4 (1)

You’re casting in the wrong place.
This:
(unsigned int) (temperature_offset>>16))
says «shift temperature_offset right sixteen bits, and THEN cast to an unsigned integer».
You need to cast BEFORE the shift, so:
((unsigned int) temperature_offset>>16))

I also post at: PicForum
To get a useful answer, always state which PIC you are using!

#2

1and0

Access is Denied

  • Total Posts : 15910
  • Reward points : 0
  • Joined: 2007/05/06 12:03:20
  • Location: Harry’s Gray Matter
  • Status: offline

Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)


2020/11/18 23:46:34

(permalink)

5 (1)

ric
You need to cast BEFORE the shift, so:
((unsigned int) temperature_offset>>16))

Shifting a 16-bit int right 16 bits is not going to work as expected. ;)

#3

1and0

Access is Denied

  • Total Posts : 15910
  • Reward points : 0
  • Joined: 2007/05/06 12:03:20
  • Location: Harry’s Gray Matter
  • Status: offline

Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)


2020/11/18 23:52:18

(permalink)

0

chowam01
I am trying to cast float to bitwise int in C. Here’s my code snippet:
write_eeprom(INDEX_CONFIG_TEMPERATURE_OFFSET_HIGH_INT, (unsigned int) (temperature_offset>>16));
write_eeprom(INDEX_CONFIG_TEMPERATURE_OFFSET_LOW_INT, (unsigned int) (temperature_offset));

I am getting the following error:
error: invalid operands to binary >> (have ‘float’ and ‘int’),

while trying to compile. Here, temperature_offset is a float type and I am trying to cast it as high int and low int as I am trying to save data in EEPROM in 16-bit chunks (as I am using a 16-bit microcontroller). I know that the ‘>>’ does not apply to float types. How can I fix this issue? I tried using a separate unsigned int variable called temperature_offset_int and then I used memcpy to cast the float into it. However, my MPLAB IDE displays an error message ‘unexpected token’ when I use the following:

memcpy(&temperature_offset_int, &temperature_offset, sizeof temperature_offset);

Does anyone know a solution to this problem?

I believe you want to save the 32-bit floating point number and not just the integer part of the number. If so, use this:


    (*(unsigned long *)&temperature_offset) >> 16;
    (*(unsigned long *)&temperature_offset) & 0xFFFF;

#4

ric

Super Member

  • Total Posts : 35931
  • Reward points : 0
  • Joined: 2003/11/07 12:41:26
  • Location: Australia, Melbourne
  • Status: offline

Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)


2020/11/19 00:08:18

(permalink)
☄ Helpfulby chowam01 2020/11/23 21:02:12

2 (1)

1and0

ricYou need to cast BEFORE the shift, so:((unsigned int) temperature_offset>>16))

Shifting a 16-bit int right 16 bits is not going to work as expected. ;)  

Good point. I didn’t notice which sub forum this was in, and assumed 32 bit ints.
I wish everyone shifted to stdint definitions.

I also post at: PicForum
To get a useful answer, always state which PIC you are using!

#5

1and0

Access is Denied

  • Total Posts : 15910
  • Reward points : 0
  • Joined: 2007/05/06 12:03:20
  • Location: Harry’s Gray Matter
  • Status: offline

Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)


2020/11/19 05:10:52

(permalink)
☄ Helpfulby chowam01 2020/11/23 21:06:27

0

ric
I wish everyone shifted to stdint definitions.

Agreed.

 This should be more efficient than my Post #4:


    (*((unsigned int *)&temperature_offset + 1));
    (*(unsigned int *)&temperature_offset);

#6

ric

Super Member

  • Total Posts : 35931
  • Reward points : 0
  • Joined: 2003/11/07 12:41:26
  • Location: Australia, Melbourne
  • Status: offline

Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)


2020/11/19 12:23:17

(permalink)

0

Is that going to work at all when the variable is a float that is being cast to an integer???

I also post at: PicForum
To get a useful answer, always state which PIC you are using!

#7

1and0

Access is Denied

  • Total Posts : 15910
  • Reward points : 0
  • Joined: 2007/05/06 12:03:20
  • Location: Harry’s Gray Matter
  • Status: offline

Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)


2020/11/19 13:17:35

(permalink)

4 (1)

ric
Is that going to work at all when the variable is a float that is being cast to an integer???

You mean this?

float foo;
int32_t foo_int;
uint16_t hiword, loword;

     foo = 123456.789;  // 0x47F12065
    foo_int = (int32_t) foo;  // 123456 = 0x0001E240

    hiword = (*((uint16_t *)&foo_int + 1));  // 0x0001
    loword = (*(uint16_t *)&foo_int);        // 0xE240

#8

#include <stdio.h>

void print_line(int index, int cents, int value)
{
    float count = (float)cents / (float)value;
    float dollar_part = (float)value / 100;
    float cents_part = (float) value % 100;
    printf("| %-2d | %9f.%02f | %5f |n", index, dollar_part, cents_part, count);
}

void coins(int cents)
{
    printf("You did not type in the correct format in terms of dollars and cents.n");
    printf("n+----+--------------+-------+n");
    printf("| #  | Denomination | Count |n");
    printf("+----+--------------+-------+n");
    print_line(1, cents, 10000);
    cents = cents % 10000;
    print_line(2, cents, 5000);
    cents = cents % 5000;
    print_line(3, cents, 1000);
    cents = cents % 1000;
    print_line(4, cents, 500);
    cents = cents % 500;
    print_line(5, cents, 200);
    cents = cents % 200;
    print_line(6, cents, 100);
    cents = cents % 100;
    print_line(7,  cents, 50);
    cents = cents % 50;
    print_line(8, cents, 20);
    cents = cents % 20;
    print_line(9, cents, 10);
    cents = cents % 10;
    print_line(10,cents, 5);
    cents = cents % 5;
    print_line(11, cents, 1);
    cents = cents % 1;

    printf("+----+--------------+-------+n");

    printf("n+----+--------------+-------+n");
    printf("| #  | Denomination | Count |n");
    printf("+----+--------------+-------+n");
    print_line(1, cents, 10000);
    cents = cents % 10000;
    print_line(2, cents, 5000);
    cents = cents % 5000;
    print_line(3, cents, 1000);
    cents = cents % 1000;
    print_line(4, cents, 500);
    cents = cents % 500;
    print_line(5, cents, 200);
    cents = cents % 200;
    print_line(6, cents, 100);
    cents = cents % 100;
    print_line(7,  cents, 50);
    cents = cents % 50;
    print_line(8, cents, 20);
    cents = cents % 20;
    print_line(9, cents, 10);
    cents = cents % 10;
    print_line(10,cents, 5);
    cents = cents % 5;
    print_line(11, cents, 1);
    cents = cents % 1;

    printf("+----+--------------+-------+n");

    printf("n+----+--------------+-------+n");
    printf("| #  | Denomination | Count |n");
    printf("+----+--------------+-------+n");
    print_line(1, cents, 10000);
    cents = cents % 10000;
    print_line(2, cents, 5000);
    cents = cents % 5000;
    print_line(3, cents, 1000);
    cents = cents % 1000;
    print_line(4, cents, 500);
    cents = cents % 500;
    print_line(5, cents, 200);
    cents = cents % 200;
    print_line(6, cents, 100);
    cents = cents % 100;
    print_line(7,  cents, 50);
    cents = cents % 50;
    print_line(8, cents, 20);
    cents = cents % 20;
    print_line(9, cents, 10);
    cents = cents % 10;
    print_line(10,cents, 5);
    cents = cents % 5;
    print_line(11, cents, 1);
    cents = cents % 1;

    printf("+----+--------------+-------+n");

}

int main(void)
{
    int dollars, cents;
    printf("Please enter total value: ");
    int n = scanf("%d.%d", &dollars, ¢s);
    if (n != 2)
    {
        printf("You did not type in the correct format in terms of dollars and cents.n");
    }
    else if (dollars < 0)
    {
        printf("You did not type in the correct format in terms of dollars and cents.n");
    }
    else if (cents < 0 || cents > 99)
    {
        printf("You did not type in the correct format in terms of dollars and cents.");
    }
    else
    {
        int total_cents = dollars * 100 + cents;
        coins(total_cents);
    }
return 0;


    printf("main()n");
}

My code looks like this. For line

float cents_part = (float)value % 100;

it gives an error

invalid operands to binary % (have ‘float’ and ‘int’)

. How do I fix this?

What I have tried:

Honestly I’m quite lost, still new to this for school.

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

int main (void) {
    printf ("Please enter the change owed:"); 
    float amount = GetFloat(); 

    if (amount < 0) {
        printf ("Please enter a positive integar for the change"); 
    }

    float amountInCents = round(amount * 100); 

    if (amountInCents > 25) {
     float Quater_Coins = amountInCents % 25;
     printf("Number of $0.25 coins used = %f", Quater_Coins); 
 }


}

I keep getting this error:

clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow    greedy.c  -lcs50 -lm -o greedy
**greedy.c:16:41: error: invalid operands to binary expression ('float' and 'float')
float Quater_Coins = amountInCents % 25;
                     ~~~~~~~~~~~~~ ^ ~~** 1 error generated. make: *** [greedy] Error 1

Cliff B's user avatar

Cliff B

66.2k4 gold badges31 silver badges56 bronze badges

asked Feb 7, 2016 at 19:14

Mohammed Shayan Khan's user avatar

The % operator only works with integers, so you’ll want to convert your float to an integer. That’s kind of the purpose of round(), to round off the float so it can be applied to an int variable.

answered Feb 7, 2016 at 19:41

Fobok's user avatar

FobokFobok

829 bronze badges

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

  • Home
  • Forum
  • General Programming Boards
  • C Programming
  • invalid operands to binary?

  1. 12-15-2012


    #1

    Thomas_W is offline


    Registered User


    invalid operands to binary?

    The following lines of code from a function of mine is producing the output (this is just for a couple of the error lines but its all like this):

    hours_3b.c:151: error: invalid operands to binary + (have ‘float *’ and ‘float’)
    hours_3b.c:153: error: invalid operands to binary + (have ‘float *’ and ‘double’)

    Here is the code for the function:

    Code:

    if (employeeData[i].hours > STD_HOURS) {
      total_grossOT += employeeData[i].gross;
      /*Calculates sum total of gross pay */
      total_OT += (employeeData[i].hours - STD_HOURS);
      /*Calculates sum total of OT */
      total_hours += (employeeData[i].hours + employeeData[i].OT);
      /*Calculates sum total of hours */
    }
    
    else {
      employeeData[i].OT = 0;
    
      total_gross += (employeeData[i].wage_rate * employeeData[i].hours);
      /*Calculates the sum total of gross pay */
      total_hours += employeeData[i].hours;
      /*Calculates sum total of hours */
    }

    Im trying to figure out why this is happening. All of the variables being used are of type float.

    Last edited by Salem; 12-15-2012 at 10:39 PM.

    Reason: fixed tags


  2. 12-15-2012


    #2

    whiteflags is offline


    Lurking

    whiteflags's Avatar


    Actually, let me put that a different way. Double check the type of thing that you are adding.

    c = a + b;
    For the best results, c, a and b should all be the same type.

    And that type needs to match exactly the type in the binary + operator declaration:

    Code:

    type& operator + (const type& a, const type& b);

    You’re going to have confusing problems if type is different in places. (Like using pointers)

    Last edited by whiteflags; 12-15-2012 at 09:48 PM.


  3. 12-15-2012


    #3

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    > All of the variables being used are of type float.
    Your error messages beg to differ.

    > hours_3b.c:151: error: invalid operands to binary + (have ‘float *’ and ‘float’)
    > hours_3b.c:153: error: invalid operands to binary + (have ‘float *’ and ‘double’)
    Something in each one of them is a pointer.

    Did you forget a subscript.


  4. 12-16-2012


    #4

    c99tutorial is offline


    Registered User


    What are the types of total_grossOT, total_OT, total_hours, etc.? As was mentioned by your compiler, the one on the left-hand side is a float *, not a float. Try changing the offending line to include a pointer dereference. For example, assuming line 151 has the total_grossOT line, then you can change it to

    *total_grossOT += some_float_arg;

    That kind of fix should at least remove the compiler error, but it may still have the wrong logic. Pointers must be pointing to some valid memory for that type before you dereference it. If you’re just now discovering it’s a pointer, you might have forgotten to do this.


Popular pages

  • Exactly how to get started with C++ (or C) today
  • C Tutorial
  • C++ Tutorial
  • 5 ways you can learn to program faster
  • The 5 Most Common Problems New Programmers Face
  • How to set up a compiler
  • 8 Common programming Mistakes
  • What is C++11?
  • Creating a game, from start to finish

Recent additions subscribe to a feed

  • How to create a shared library on Linux with GCC — December 30, 2011
  • Enum classes and nullptr in C++11 — November 27, 2011
  • Learn about The Hash Table — November 20, 2011
  • Rvalue References and Move Semantics in C++11 — November 13, 2011
  • C and C++ for Java Programmers — November 5, 2011
  • A Gentle Introduction to C++ IO Streams — October 10, 2011

Similar Threads

  1. Replies: 3

    Last Post: 05-06-2012, 04:27 AM

  2. Replies: 12

    Last Post: 03-18-2008, 09:21 AM

  3. Replies: 8

    Last Post: 03-31-2007, 11:15 PM

  4. Replies: 3

    Last Post: 12-03-2005, 11:21 PM

  5. Replies: 14

    Last Post: 09-13-2005, 04:59 PM

Понравилась статья? Поделить с друзьями:
  • Error invalid operands to binary expression float and float
  • Error invalid operands of types float and int to binary operator
  • Error invalid operands of types double and int to binary operator
  • Error invalid operands of types double and double to binary operator
  • Error invalid operands of types const char and char to binary operator