Error invalid operands to binary have float and int

#include int main(void) { float with; float inacbal; float acleft; scanf("%f",&with); scanf("%f",&inacbal); if((with%5)==0)//error here {
#include <stdio.h>

int main(void) 
{
    float with;
    float inacbal;
    float acleft;
    scanf("%f",&with);
    scanf("%f",&inacbal);
    if((with%5)==0)//error here
    {
        acleft=inacbal-with-0.50;
        printf("%f",acleft);
    }
    else
        printf("%f",inacbal);
    return 0;
}

lurker's user avatar

lurker

56.2k9 gold badges68 silver badges101 bronze badges

asked Sep 18, 2014 at 13:44

Dumb's user avatar

5

float with;
if((with%5) == 0)

is incorrect. You can apply % only to integers. If you really want to do a modulo operation on float, then use fmod or if you’re not bothered about the sign of the remainder, then use the new IEEE 754r mandated C99’s remainder. From Sun’s Numerical Computation Guide:

The remainder(x,y) is the operation specified in IEEE Standard 754-1985. The difference between remainder(x,y) and fmod(x,y) is that the sign of the result returned by remainder(x,y) might not agree with the sign of either x or y, whereas fmod(x,y) always returns a result whose sign agrees with x.

answered Sep 18, 2014 at 13:46

legends2k's user avatar

legends2klegends2k

30.8k24 gold badges118 silver badges215 bronze badges

8

You are getting that error because you can’t use the modulus operator (%) with float.

If you want to calculate the remainder of it,use fmod() like this:

fmod(with,5);

fmod will return the remainder of the division. Don’t forget to include math.h in order to use fmod.

answered Sep 18, 2014 at 13:56

Spikatrix's user avatar

SpikatrixSpikatrix

20.1k7 gold badges40 silver badges81 bronze badges

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?

Jean-François Fabre's user avatar

asked Nov 18, 2020 at 21:35

Holebas's user avatar

Create a separate unsigned int variable and memcpy the float into it, then work on that.

unsigned int temperature_offset_int;
memcpy(&temperature_offset_int, &temperature_offset, sizeof(temperature_offset));
write_eeprom(INDEX_CONFIG_TEMPERATURE_OFFSET_HIGH_INT, temperature_offset_int >> 16);
write_eeprom(INDEX_CONFIG_TEMPERATURE_OFFSET_LOW_INT, temperature_offset_int & 0xffff);

answered Nov 18, 2020 at 21:42

dbush's user avatar

dbushdbush

199k21 gold badges210 silver badges262 bronze badges

1

20SERGEJKA02

0 / 0 / 0

Регистрация: 02.11.2019

Сообщений: 21

1

09.11.2019, 10:13. Показов 3365. Ответов 3

Метки нет (Все метки)


Что это за ошибка в Code Blocks: error: invalid operands to binary % ( have ‘float’ and ‘int’) — в 65-й строке

C
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <locale.h>
#include <time.h>
 
const int N=10;
 
int random(int S)
{
    return rand()%S;
}
 
main()
{
    setlocale(LC_ALL, "rus");
    time_t t;
    srand((unsigned)time(&t));
 
    int O[N], i, a, b, j, x, w;
    a=-5;
    b=10;
    w=0;
 
    for(i=0; i<N; i++)
    {
        O[i]=random (b-a+1)+a;
    }
 
    printf("n                              Массив 'O' целых чисел:nn");
    for(i=0; i<N; i++)
        printf("%3dn", O[i]);
 
 
    float Q[N], n, m;
    n=-5;
    m=10;
 
    for(j=0; j<N; j++)
    {
        Q[j]=rand()*(m-n)/RAND_MAX+n;
    }
 
    printf("nn                          Массив 'Q' действительных чисел:nn");
    for(j=0; j<N; j++)
        printf("%10fn", Q[j]);
    printf("n");
 
 
    printf("n                     Минимальный элемент и номер массива 'O'n");
    for (x=0; x<N; x++)
        {
            O[x]=O[x]%100;
 
            if (O[x]<O[w])
            w=x;
        }
    printf("nМассив №%d: %dn", w, O[w]);
    printf("n");
 
 
    int e, c, o;
    for (e=0; e<N; e++)
        {
            Q[e]=Q[e]%10-5;
            printf("%dn", Q[e]);
        }
    e=0;
    o=N;
    while(e<o)
        if(Q[e]<0)
        {
            o-=1;
            for(c=e; c<o; c++)
                Q[c]=Q[c+1];
        }
        else
            e+=1;
 
        for(e=0; e<o; e++)
            {
                printf("%dn", Q[e]);
            }
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Диссидент

Эксперт C

27209 / 16962 / 3749

Регистрация: 24.12.2010

Сообщений: 38,148

09.11.2019, 13:16

2

20SERGEJKA02, Операция взятия остатка «%» определена только для целых чисел (типы char, bnt, long). А ты делишь на double



0



0 / 0 / 0

Регистрация: 02.11.2019

Сообщений: 21

09.11.2019, 15:04

 [ТС]

3

Так а что мне делать???
Что писать???



0



550 / 383 / 125

Регистрация: 02.10.2008

Сообщений: 1,553

Записей в блоге: 1

10.11.2019, 18:23

4

А что мы должны делать в 65й строке?

Возможно поможет man 3 fmod



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.

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;
}

Skip to main content

Forum for Electronics

Forum for Electronics

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals… and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

  • Groups

  • Uncategorized

  • Pic microcontroller projecta

  • Social Groups

  • Social Groups Discussions

  • Pic microcontroller projecta

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Pic microcontroller projecta

Pic microcontroller projecta

Share this group

Quick Overview

Category
Uncategorized
Language
Total members
40
Total events
0
Total discussions
2
Total views
17K
Total albums
0

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

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

Status
Not open for further replies.

  • #1

Newbie level 1

Joined
Nov 18, 2020
Messages
1
Helped
0
Reputation

0

Reaction score
0
Trophy points
1
Activity points

19


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?

  • #2

Hi,

I’m not much experienced with C…
Generally I’d avoid to store «float» values in EEPROM. I’d rather use integer.
This does not mean that in your code you can wirk only with integer temperature offset (steps of 1),
You may use two 8 bit values so you are able to calibrate for -128 …. +127, with resolution of 0.004°C
* HIGH byte, integer value, as integer degree
* LOW byte integer value, but represented as 1/256 degree per LSB..

***
But if you want to use float, then you may do this:
A float usually is a 32bit value = 4 bytes.
So you may fool C by treating the «float» as an array of 4 bytes.

Write a function that expects a pointer to an (4 byte) array.
It takes byte by byte and stores it into the EEPROM.

If you now call this function, but pass the pointer to your float…
(The compiler will issue a warning you may ignore)
Then your function will treat the float just as 4 bytes and store them into the EEPROM.

There will be better solutions … but this is a workaround that I could use in my limited knowledge of C and its available library functions.
******

Klaus

  • #3

Firstly you can’t tell a float to shift a fractional place at bit level because floats are not stored as simple binary representations, they are stored more akin to exponent and mantissa.

The method I use is to create a union of the float and appropriate number of ‘char’ bytes. Then storing the individual bytes will store the component parts of the float instead of the number as a whole.

Brian.

  • #4

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));

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

A shift right operation can’t be performed on a float, use a divide by 65536.
I kind of suspect that you don’t really want to shift right by 16.

The float type is comprised of an exponential and a fractional part so if you treated it like an int and performed a right shift the value would no longer be correct as you aren’t adjusting the exponent.

Your use of float was probably a poor choice as you are probably getting the input temperature as some sort of fixed point or offset binary value from some sensor and should have just scaled it instead of converting to float.

Status
Not open for further replies.
  • Groups

  • Uncategorized

  • Pic microcontroller projecta

  • Social Groups

  • Social Groups Discussions

  • Pic microcontroller projecta

  • This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
Error: invalid operands of types 'int' and 'float*' to binary'operator/'
int *average = new int((num) / data);

показывая для этой строки кода.
Почему так?

float *data;
int num;
int mode;
double average, median;

cout << "How many students were surveyed?  ";
cin >> num;
data = makeArray(num);

float getAverage(float *data, int num)
{
int *average = new int((data) / num);
return *average;
}

1

Решение

Это означает, что вы сравниваете два несовместимых типа вместе. Один из num а также data является intа другой float*, В зависимости от поведения, которое вы хотите, вы захотите

  1. Разыменуйте указатель, как в *x для того, что x это указатель
    2а. Вы хотите разыграть int к float за floating point divisionгде результат преобразуется обратно в int
    2b. Вы хотите разыграть float для int, за integer division, который затем будет преобразован обратно в int,

Обновить
Поскольку вы обновили свой код, я укажу на большую проблему; у тебя сейчас утечка памяти.

Я бы посоветовал вам вместо этого возвратить ваше целое число по значению и, возможно, передать по ссылке или константе ссылки и избегать указателей целиком, но более того, я бы предложил некоторую симметрию в ваших входных параметрах, а также правильность констант:

//your code:
float getAverage( float *data, int sum )
{
//data is a float* and needs to be de-ref'd and casted to int for float but isnt
int *average = new int( (data) / num );
//note that now average is a pointer to a newly constructed int that will never be free'd
return *average;  //because you return it here, where the value will then be implicily converted to a float and be mostly worthless.
}

// In both suggestions I will use symmetric types, I will not introduce dynamic memory and I will use floating point division for maximal accuracy.

// Suggestion one use Const References
float getAverage( const float &data, const int &num)
{
float result = data / (float) num;
return result;
}

// Suggestion two use pointers to constants
float getAverage( const float *data, const int *num )
{
float result = (*data) / float(*num);
return result;
}

// Suggestion three pass by value since primitives are cheap
float getAverage( float data, int num)
{
float result = data / (float) num;
return result;
}

1

Другие решения

Других решений пока нет …

Понравилась статья? Поделить с друзьями:
  • 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