#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
56.2k9 gold badges68 silver badges101 bronze badges
asked Sep 18, 2014 at 13:44
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
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
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?
asked Nov 18, 2020 at 21:35
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
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-й строке
__________________
0 |
Диссидент 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
0
I am trying to cast float to bitwise int in C. Here’s my code snippet: I am getting the following error: 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
|
ric
Super Member
Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)
4 (1) You’re casting in the wrong place. I also post at: PicForum #2 |
1and0
Access is Denied
Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)
5 (1)
Shifting a 16-bit int right 16 bits is not going to work as expected. #3 |
1and0
Access is Denied
Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)
0
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:
#4 |
ric
Super Member
Re: error: invalid operands to binary >> (have ‘float’ and ‘int’) 2 (1)
Good point. I didn’t notice which sub forum this was in, and assumed 32 bit ints. I also post at: PicForum #5 |
1and0
Access is Denied
Re: error: invalid operands to binary >> (have ‘float’ and ‘int’) 0
Agreed. This should be more efficient than my Post #4:
#6 |
ric
Super Member
Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)
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 #7 |
1and0
Access is Denied
Re: error: invalid operands to binary >> (have ‘float’ and ‘int’)
4 (1)
You mean this? float foo; #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
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 should upgrade or use an alternative browser.
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
- Joined
- Nov 18, 2020
- Messages
- 1
- Helped
- 0
- Reputation
-
0
- Reaction score
- 0
- Trophy points
- 1
- Activity points
-
19
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
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
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*
, В зависимости от поведения, которое вы хотите, вы захотите
- Разыменуйте указатель, как в
*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
Другие решения
Других решений пока нет …