Error invalid operands of types float and int to binary operator

I'm getting the error invalid operands of types 'float' and 'int' to binary 'operator^' and I'm not sure how to fix it The error occurs in the function f, in the last line Any help is much apprec...

I’m getting the error invalid operands of types ‘float’ and ‘int’ to binary ‘operator^’ and I’m not sure how to fix it

The error occurs in the function f, in the last line

Any help is much appreciated

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>


using namespace std;
float f(float x);

int main()
{

    float a;
    float b;
    int n;
    float h;
    float x;
    float area;

    cout << "Please input the first limit: ";
    cin >> a;
    cout << "Please input the second limit: ";
    cin >> b;
    cout << "How many rectangles do you want to use? ";
    cin >> n;

    h = (b-a)/n;

    area = (f(a)+f(b))/2;

    for (int i=1;i<n;i++) {
        area += f(a+i*h);
    }

    area = area*h;
    cout << "The area under the curve of f(x) = (2/sqrt(3.14))(exp(-x^2)) is ";
    cout << area;
}

float f(float x){
     return (exp(-x^2))(2/sqrt(3.14));
}

asked Mar 24, 2016 at 19:59

Jonathan Parkes's user avatar

1

x has the data type float. You have applied the logical XOR operator to it. XOR requires integer operands.

I suspect you’re looking for an exponent, though. C++ has no exponent operator. Instead, try something like this:

float f(float x){
     return (exp(-(x*x)))*(2/sqrt(3.14));
}

I assume that you mean to multiply exp(-(x*x)) by (2/sqrt(3.14), but I didn’t see a multiplication operator there.

answered Mar 24, 2016 at 20:02

Logicrat's user avatar

LogicratLogicrat

4,42814 silver badges22 bronze badges

7

I found answers for other operators but it seems like % has its own properties:

#include <iostream>
#include <cmath>

using namespace std;

int main()

{
float pprice;
cout << "Enter the purchase price =>" << endl;
cin >> pprice;
float cash = 10000%pprice;
return 0;
}

//Error: invalid operands of types ‘int’ and ‘float’ to binary ‘operator%’

This is only a sample of the code which displays the same error. Please how can I fix this error?

danday74's user avatar

danday74

49.9k48 gold badges222 silver badges270 bronze badges

asked Apr 26, 2016 at 1:21

Abdul's user avatar

1

The % operator only works on type int (See here). For float you need to use fmod.

Community's user avatar

answered Apr 26, 2016 at 1:23

Fantastic Mr Fox's user avatar

Fantastic Mr FoxFantastic Mr Fox

31.5k26 gold badges92 silver badges171 bronze badges

Terminator004

3 / 2 / 1

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

Сообщений: 501

1

10.02.2018, 18:52. Показов 14149. Ответов 7

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


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  float n,m,k;
        cout << "Kiek vairotojas is sandelio turi parvezti deziu i parduotuve?: ";
        cin >> n;
        cout << "Kiek i masina telpa deziu?: ";
        cin >> m;
        if(n <= m){
            cout << "I masina telpa dezes. I masina gali tilpti dar: " <<m-n << "dezes" << endl;
        }
        if(n > m){
                 k = n / m;
                k++;
                if(k % 2 == 0){
                    k--;
                }
            cout << "I masina netelpa dezes. Reiketu dar " << k << " kartu nuvaziuoti i sandeli" << endl;
 
        }

Ошибка вот тут:

C++
1
if(k % 2 == 0){

Система пишет:error: invalid operands of types ‘float’ and ‘int’ to binary ‘operator%’
Помогите исправить.

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



0



Даценд

Эксперт .NET

5858 / 4735 / 2940

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

Сообщений: 8,361

10.02.2018, 20:05

2

Terminator004,
Объявите k как int.

C++
1
2
float n, m;
int k;



0



3 / 2 / 1

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

Сообщений: 501

10.02.2018, 20:16

 [ТС]

3

Цитата
Сообщение от Даценд
Посмотреть сообщение

Объявите k как int.

Даценд, но мне нужен float, потому что, k это ответ, и он может выйти с запятой, а инт уберет всё, что после запятой.



0



Вездепух

Эксперт CЭксперт С++

10435 / 5704 / 1553

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

Сообщений: 14,100

10.02.2018, 20:18

4

Цитата
Сообщение от Terminator004
Посмотреть сообщение

Помогите исправить.

Удалите из программы весь процитированный вами код — эта ошибка пропадет.

Добавлено через 1 минуту

Цитата
Сообщение от Terminator004
Посмотреть сообщение

но мне нужен float, потому что, k это ответ, и он может выйти с запятой,

Что вы тогда хотели сказать своим k % 2? Как мы можем вам «помочь исправить» код, который изначально бессмыслен?



0



Эксперт .NET

5858 / 4735 / 2940

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

Сообщений: 8,361

10.02.2018, 20:23

5

Цитата
Сообщение от Terminator004
Посмотреть сообщение

k это ответ, и он может выйти с запятой

Тогда объясните, что вернет операция k%2, если k равен, к примеру 2.5?
Ибо ни я ни компилятор этого не понимаем.
О! И TheCalligrapher не понимает.



0



Terminator004

3 / 2 / 1

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

Сообщений: 501

10.02.2018, 20:33

 [ТС]

6

Цитата
Сообщение от Даценд
Посмотреть сообщение

Тогда объясните, что вернет операция k%2, если k равен, к примеру 2.5?
Ибо ни я ни компилятор этого не понимаем.
О! И TheCalligrapher не понимает.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
   float n,m,k;
        cout << "Сколько водитель со склада, должен привезти ящиков в магазин?: ";
        cin >> n;
        cout << "Сколько в машину поместится ящиков: ";
        cin >> m;
        if(n <= m){
            cout << "В машину ящики поместятся. В машину, ещё может поместится " <<m-n << " ящиков" << endl;
        }
        if(n > m){
                 k = n / m;
                k++;
                if(k % 2 == 0){
                    k--;
                }
            cout << "В машину не поместятся ящики. Нужно ещё " << k << " раз ехать на склад" << endl;
 
        }

На русский перевёл. Ну и ясно тут всё, если перво ввожу 140, а машину поместится допустим 20, так ещё надо будет 7 раз ехать, чтоб все ящики перевести. Но, если написать 141. а поместится 20, так 1 ящик лишний и из-за него должен авто 8 раз ехать. Так вот, я проверяю, если число без запятых, то тогда так и вывести, но если с запятой, значит сколько-то ящиков ещё осталось и нужно +1 раз добавить.



0



TheCalligrapher

Вездепух

Эксперт CЭксперт С++

10435 / 5704 / 1553

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

Сообщений: 14,100

10.02.2018, 20:41

7

Лучший ответ Сообщение было отмечено Terminator004 как решение

Решение

Цитата
Сообщение от Terminator004
Посмотреть сообщение

Так вот, я проверяю, если число без запятых, то тогда так и вывести, но если с запятой, значит сколько-то ящиков ещё осталось и нужно +1 раз добавить.

Плавающее вычисления остатка делает функция fmod.

Но вы занимаетесь фигней. Вам нужно просто выполнить целочисленное деление n на m с округлением вверх. Требуемое количество поездок равно

C++
1
int k = (n + m - 1) / m;

и не надо никакого ветвления, float, % и fmod.



1



3 / 2 / 1

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

Сообщений: 501

10.02.2018, 20:50

 [ТС]

8

Цитата
Сообщение от TheCalligrapher
Посмотреть сообщение

int k = (n + m — 1) / m;

TheCalligrapher, хорошо работает, спасибо за помощь



0



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

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

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

  • Forum
  • General C++ Programming
  • What does» invalid operands of types `in

What does» invalid operands of types `int’ and `double’ to binary `operator%’ «

Hello, Im a complete newbie to c++, so i would appriciate any help. I keep getting these errors in my program.
37 invalid operands of types `int’ and `double’ to binary `operator%’
i dont understand the problem, all of my varibles are ints.

//this program calculates the number of quarters,
// dimes and nickles and pennies are nessasary to
//generate the number of cents imputed
#include <iostream.h>
#include<string.h>

int main()
{
int toBeChanged, numberOfDimes, numberOfQuarters, numberOfNickels, numberOfPennies;
cout << » I will show you how many quarters, dimes, nickels, and npennies needed to make the amount. How much money do you have?» << ‘n’;
cin >> toBeChanged;

if(toBeChanged >= .25)
{
numberOfQuarters = (int) (toBeChanged / .25);
toBeChanged = (toBeChanged % .25);
}

if(toBeChanged >= .1)
{
numberOfDimes = (int) (toBeChanged / .1);
toBeChanged = (toBeChanged % .1);
}

if(toBeChanged >= .05)
{
numberOfNickels = (int) (toBeChanged / .05);
toBeChanged = (toBeChanged % .05);
}

if(toBeChanged >= .01)
{
numberOfPennies = (int) (toBeChanged / .01);
toBeChanged = toBeChanged % .01;
}

cout << «For «<< toBeChanged << » you will need:»<<‘n’;
cout <<numberOfQuarters<< » quarters,»<<‘n’;
cout << numberOfDimes << » dimes,»<< ‘n’;
cout << numberOfNickels << » nickels,»<< ‘n’;
cout << numberOfPennies << » pennies.»<< ‘n’;

system(«pause»);
return 0;
}

variables: toBeChanged, numberOfDimes, numberOfQuarters, numberOfNickels, numberOfPennies;

should be float I think, cos you’re losing floating points.

I could be wrong… I am still learning C++, but I believe the ‘%’ or ‘modulus’ only works on values of an ‘int’ data type… I actually worked through a problem like this a bit ago… let me see if I can’t find the file and see how I did this…

it looks like i used a ‘const’ or ‘constants’ in my code… and where you have a decimal to represent change, i used the constant variable identifier…

const int HALFDOLLAR = 50; // a constant

change = change % HALFDOLLAR; // my assignment statement

Last edited on

mjmckechnie is correct. The modulo operator needs an int (>0, unless your head just doesn’t hurt as much as you want it to) as argument.

@ codekiddy
yea they started out as floats, then doubles. But my % inst working with either.
i did try to convert it to float and i get
invalid operands of types `float’ and `double’ to binary `operator%’

@ mjmckechnie
thank you, any help is very appriciated.

@ mjmckechnie
thank you, any help is very appriciated.

Does that mean you still need help?

Actually the message waas suppose to nbe sent after you said you’d look. but yes i still need some guidence.
ive tried making my varibles const int as so

numberOfQuarters = (int) (toBeChanged / .25);
toBeChanged = (const int)(toBeChanged % .25);

and im still etting the same errors.

invalid operands of types `int’ and `double’ to binary `operator%’

.25 is a double

Yes, but i cant use double with a %.

Yes that is your problem.

If you want to do mod on floating point numbers you can use std::fmod. I have not studied your code in detail so I don’t know if this is what you want.

Last edited on

So then i guess my question becomes
what do i use instead of a mod operation that will work the same with doubles?

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
	//Header file
#include <iostream>

using namespace std;

	//Named constants
const int HALFDOLLAR = 50;
const int QUARTER = 25;
const int DIME = 10;
const int NICKEL = 5;

int main()
{
		//Declare variable
	int change;

	cout << "Enter change in cents: ";		
	cin >> change;							
	cout << endl;

	cout << "The change you entered is " << change << endl;		

	cout << "The number of half-dollars to be returned is " << change / HALFDOLLAR << endl;		

	change = change % HALFDOLLAR;		

	cout << "The number of quarters to be returned is " << change / QUARTER << endl;		

	change = change % QUARTER;		

	cout << "The number of dimes to be returned is " << change / DIME << endl;		

	change = change % DIME;		

	cout << "The number of nickels to be returned is " << change / NICKEL << endl;		

	change = change % NICKEL;		

	cout << "The number of pennies to be returned is " << change << endl;		

	cout << endl << "Please press enter to exit the program...";

	cin.get();

	return 0;
}

generally, I believe that in learning to program we are supposed to look at other peoples code, and that will help us to learn. At the same time, I don’t know if it is frowned upon to give you the whole answer or not here at this forum. But, here it is, this is the way I did it…

you can also write the assignment expression «change = change % NICKEL» like this, change «change %= NICKEL». It is just a simplified way of doing the same thing.

Hope it helps and that you learn something from it… :)

Last edited on

Thank you mjmckechnie,
it does help to look at other similar codes. yes this seems much more of a simple way of writing this program.
i rewrote my program a bit, but it still is kinda freaking out.
but at least i dont have the errors anymore

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
//this program calculates the number of quarters,
// dimes and nickles and pennies are nessasary to 
//generate the number of cents imputed
#include <iostream.h>
#include<string.h>

main() 
{
     double toBeChanged; 
     int numberOfDimes, numberOfQuarters, numberOfNickels, numberOfPennies;
     cout << " I will show you how many quarters, dimes, nickels, and npennies needed to make the amount. nHow much money do you have? (i.e. 1.25)" << 'n';
     cin >> toBeChanged;
     
cout << "For "<< toBeChanged << " you will need:"<<'n';  
   
     toBeChanged = toBeChanged * 100;
          
      if(toBeChanged >= 25)
{
      numberOfQuarters =  (toBeChanged / 25);
      toBeChanged = (int)toBeChanged % 25;
}

      if(toBeChanged >= 10)
{
               numberOfDimes = (toBeChanged / 10);
               toBeChanged = (int)toBeChanged % 10;
}

               if(toBeChanged >= 5)
{
               numberOfNickels =  (toBeChanged / 5);
               toBeChanged = (int)toBeChanged % 5;
}

               if(toBeChanged >= 1)
{
               numberOfPennies = (toBeChanged  / 1);
               toBeChanged = (int)toBeChanged % 1;
}


cout << numberOfQuarters<< " quarters,"<<'n';
cout << numberOfDimes << " dimes, "<< 'n';
cout << numberOfNickels << " nickels,"<< 'n';
cout << numberOfPennies << " pennies."<< 'n';

system("pause"); 
return 0;
}

so, it can get the quarters right, but then it messes up on the dimes and below.
any help?

Last edited on

So, if you do not initialize the variables and the change is say 785, it will only need the biggest value; which is quarters. But if you have 785.66, than all of the ‘if’ statements will work… this is why there is weird output… at least that is what I believe… I didn’t spend to much time with it…

In other words, if the value of the input is a integer (say 785), then only the first ‘if’ statement executes…
and dimes, nickles, and pennies never get initialized…

Last edited on

Topic archived. No new replies allowed.

  • #1

Имеется скетч WiFi часы. Все работало отлично. Скетч неоднократно заливался в ESP8266. Поменялось имя и пароль WiFi. Поменял в скетче. Скетч перестал компилироваться. Пробовал на трех компьютерах. Скачивал разные версии IDE.От версии 1.68 до 1.81. Скетч выдает ошибку.Вкратце ошибка выглядит так:

Arduino: 1.8.2 Hourly Build 2017/02/27 02:33 (Windows 10), Плата:»NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), v2 Lower Memory, Disabled, None, Only Sketch, 115200″
C:UsersalexeyDesktopCLOCK_ESP8266_1.inoCLOCK_ESP8266_1.ino.ino: In function ‘void updateTime()’:
CLOCK_ESP8266_1.ino:354: error: invalid operands of types ‘double’ and ‘long int’ to binary ‘operator%’
long epoch = round(curEpoch + 3600 * utcOffset + 86400L) % 86400L;
^
Несколько библиотек найдено для «ArduinoJson.h»
Используется: C:UsersalexeyDocumentsArduinolibrariesArduinoJson
Не используется: D:Arduino_IDElibrariesArduinoJson
Несколько библиотек найдено для «Wire.h»
Используется: C:UsersalexeyAppDataLocalArduino15packagesesp8266hardwareesp82662.6.0librariesWire
Не используется: D:Arduino_IDElibrariesWire
Несколько библиотек найдено для «Adafruit_Sensor.h»
Используется: C:UsersalexeyDocumentsArduinolibrariesAdafruit_Sensor
Не используется: D:Arduino_IDElibrariesAdafruit_Sensor
Несколько библиотек найдено для «Adafruit_BMP280.h»
Используется: C:UsersalexeyDocumentsArduinolibrariesAdafruit_BMP280_Library
Не используется: D:Arduino_IDElibrariesAdafruit_BMP280_Library
Несколько библиотек найдено для «TM1637.h»
Используется: D:Arduino_IDElibrariesTM1637
Не используется: C:UsersalexeyDocumentsArduinolibrariesDigitalTube
Несколько библиотек найдено для «Adafruit_GFX.h»
Используется: C:UsersalexeyDocumentsArduinolibrariesAdafruit-GFX-Library-master
Не используется: D:Arduino_IDElibrariesAdafruit-GFX-Library-master
Несколько библиотек найдено для «Max72xxPanel.h»
Используется: C:UsersalexeyDocumentsArduinolibrariesarduino-Max72xxPanel-master
Не используется: D:Arduino_IDElibrariesarduino-Max72xxPanel-master
exit status 1
invalid operands of types ‘double’ and ‘long int’ to binary ‘operator%’
Этот отчёт будет иметь больше информации с
включенной опцией Файл -> Настройки ->
«Показать подробный вывод во время компиляции»

Кроме того на старых IDE пишет «ошибка определения платы». Прошу помощи. Почему 100 процентно работающий скетч перестал компилироваться.
Система Win10.

  • 11.1 KB
    Просмотры: 28

  • #2

прям делаем поиск по строке ошибки

invalid operands of types ‘double’ and ‘long int’ to binary ‘operator%’

и попадаем сразу
Yes. % operator is not defined for double type. Same is true for bitwise operators like «&,^,|,~,<<,>>» as well.
в выражении

long epoch = round(curEpoch + 3600 * utcOffset + 86400L) % 86400L;

читаем про round()
The round() function takes a single argument and returns a value of type double, float or long double type.

как просто правда?

  • #3

прям делаем поиск по строке ошибки

и попадаем сразу
Yes. % operator is not defined for double type. Same is true for bitwise operators like «&,^,|,~,<<,>>» as well.
в выражении

читаем про round()
The round() function takes a single argument and returns a value of type double, float or long double type.

как просто правда?

Ну для кого просто,а для кого темный лес.Буду очень благодарен, если Вы исправите скетч. Я так понимаю для Вас это не составит труда.
И остается вопрос: почему этот скетч,буквально пару месяцев назад компилировался без проблем.

Сергей_Ф


  • #4

почему этот скетч,буквально пару месяцев назад компилировался без проблем.

Скорее всего поменяли ядро esp8266 и забыли. Новые ядра отличаются от старых в части аргументов многих функций.

  • #5

Скорее всего поменяли ядро esp8266 и забыли. Новые ядра отличаются от старых в части аргументов многих функций.

И что делать!?

  • #6

Библиотеки в скетче «старые». В PlatformIO версии библиотек прописаны … (поэтому сборка не развалится со временем) в Аrduino IDE беда с этим …
Вроде скетч написан для ArduinoJson.h -v.5, а сейчас …
да и другие ….
Посмотрите в именах библиотек и их версиях. Или как сказано по ядру тоже. Откатись назад по ним :)

  • #7

млин, ну уже всё рассказал и показал в каком месте ошибка.
причём тут версии прошивки?
этот код в текущем виде скомпилировать невозможно под любым компилятором. нужно делать кастинг в int
вместо

long epoch = round(curEpoch + 3600 * utcOffset + 86400L) % 86400L;

нужно

Код:

long epoch = ((int)round(curEpoch + 3600 * utcOffset + 86400)) % 86400;

а тут точно, при точно функция round нужна? может поучиться и прочитать про неё в интернете

Сергей_Ф


  • #8

Скетч неоднократно заливался в ESP8266.

код в текущем виде скомпилировать невозможно под любым компилятором

Тут точно неразрешимое противоречие.

  • #9

точно функция round нужна

Похоже не нужна. Удалил round, и скетче в строке 310 поменял float на int и все заработало.
Большое спасибо за помощь!

  • #10

Тут точно неразрешимое противоречие.

как видим да

Большое спасибо за помощь!

ну не возможно приведённый код скомпилировать, чтобы там юзернейм ни говорил.

Сергей_Ф


  • #11

@cheblin в АрдуинеИДЕ и не такое возможно. Если бы сам не сталкивался, не говорил ;)

  • #12

Ну тут явная проблема platformio. Она делает что хочет, обновляет что то сама без спроса.
Не раз сталкивался с тем что скетч написанный пару месяцев назад перестал компилироваться. Ну вот просто взял и перестал. При этом абсолютно НИЧЕГО в скетче не менялось. Скетч под гитом и любые изменения были бы видны. Но platformio что то там обновила сама по себе и абсолютно рабочий скетч перестал компилироваться. Очень нестабильная платформа.
Нет никакой уверенности что я смогу зафиксировать какое то положение вещей и через год перекомпилировать скетч пофиксив пару багов. Потому что скетч просто не скопилится и придется разбираться что там platformio обновила, какие библиотеки, ядра, компиляторы или еще что то.

  • #13

Ну тут явная проблема platformio. Она делает что хочет, обновляет что то сама без спроса.

Не к рукам, так хуже варежки :)

  • #14

Доброго времени суток. Попытался залить скетч Duino-Coin в ESP8266. Старая версия скетча компилируется без проблем, но она уже не рабочая, разработчики перетащили всё на другой сервер и переписали скетч. Дак вот, новый отказывается компилироваться. Ошибка:

ESP8266_Code:40:17: error: ‘experimental’ has not been declared
using namespace experimental::crypto;
^
ESP8266_Code:40:31: error: ‘crypto’ is not a namespace-name
using namespace experimental::crypto;
^
ESP8266_Code:40:37: error: expected namespace-name before ‘;’ token
using namespace experimental::crypto;
^
D:CoinDuino-Coin_2.4.9_windowsESP8266_CodeESP8266_Code.ino: In function ‘void loop()’:
ESP8266_Code:253:21: error: ‘SHA1’ has not been declared
String result = SHA1::hash(hash + String(iJob));
^
exit status 1
‘experimental’ has not been declared
********************************************************************************
Arduino IDE v1.8.13, библиотека 8266 — v2.4.1, свежее не поставить, так как Win7-32.

  • 4 KB
    Просмотры: 8

  • #15

ESP8266_Code:40:17: error: ‘experimental’ has not been declared
using namespace experimental::crypto;

Обновитесь в менеджере плат ESP8266 до 2.7.4 или вручную добавляйте библиотеку Crypto.h

  • #16

Обновитесь в менеджере плат ESP8266 до 2.7.4 или вручную добавляйте библиотеку Crypto.h

Было бы всё так просто… Библиотека установлена, в том то и фокус. Проверил на втором компе (Windows 7-64), результат тот же.

  • #17

Было бы всё так просто…

Не знаю сложно или просто … Загрузил ваш код в виртуалку с Win7, Arduino IDE v1.8.13, 8266 — 2.7.4 — все компилируется

  • #18

Не знаю сложно или просто … Загрузил ваш код в виртуалку с Win7, Arduino IDE v1.8.13, 8266 — 2.7.4 — все компилируется

Устанавливать библиотеку для 8266 выше 2.5.0 пробовал, выдаёт ошибку:

Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named ‘encodings’

Current thread 0x000014f0 (most recent call first):
exit status 3
Ошибка компиляции для платы Generic ESP8266 Module.

  • #19

Проверил на втором компе (Windows 7-64), результат тот же

Переустановите (или скачайте портабельную версию) IDE, обновите Java, python. Винда чистая или сборка? Попробуйте в виртуалке на чистой Windows или линухе

  • #20

SOS!

при компиляции выдаёт ошибку

  • Безымянный.png

    112.9 KB
    Просмотры: 14

Не знаю, почему я получаю эту ошибку. Это похоже на то, как a*a обрабатывает a* как указатель (float* на float* — это то же самое, что float на float). По-видимому, проблема решается, когда я объявляю a в подклассах, но дело в том, что я хочу, чтобы мои подклассы автоматически получали это от моего родительского класса.

Еще одна вещь, когда я добавляю «float a;» для каждого подкласса, который может запускать программа. Я сделал это, чтобы проверить, будет ли это работать, но нет. Поплавок a не получает значения в setA. Я только что добавил cout << a; после a = b ;.

#include"Oblik.h"
#include<cmath>

using namespace std;

class Jednakostranicni : public GeometrijskaFigura{

    float P(){
        return (a*a*sqrt(3))/4; //12    13  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'float*' and 'float*' to binary 'operator*'
    }
    float O(){
        return a+a+a; //15  12  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'float*' and 'float*' to binary 'operator+'
    }
    
};

class Kvadrat : public GeometrijskaFigura{
    
    float P(){
        return a*a;//23 12  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'float*' and 'float*' to binary 'operator*'
    }
    float O(){
        return a+a+a+a;//26 12  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'float*' and 'float*' to binary 'operator+'
    }
    
};

class Krug : public GeometrijskaFigura{
    
    float P(){
        return a*a*3.14;//34    12  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'float*' and 'float*' to binary 'operator*'
    }
    float O(){
        return 2*a*3.14;//37    12  C:UsersNameDesktopprvi.cpp  [Error] invalid operands of types 'int' and 'float*' to binary 'operator*'
    }
    
};

int main(){
    
    GeometrijskaFigura *f;
    int x;
    
    cin>>x;
    
    f->setA(x);
    
    f=new Jednakostranicni;
    cout<<"Jednakostranicni-P: "<<f->P()<<" O: "<<f->O()<<endl;
    f=new Kvadrat;
    cout<<"Kvadrat-P: "<<f->P()<<" O: "<<f->O()<<endl;
    f=new Krug;
    cout<<"Krug-P: "<<f->P()<<" O: "<<f->O()<<endl;
    
    
    
    return 1;
    
    
}

// this is Oblik.h file code
#include<iostream>

using namespace std;

class GeometrijskaFigura{
    protected: float a;
    public:
        
        void setA(float b){
         a=b;
        }
        
        virtual float P()=0;
        virtual float O()=0;
};

1 ответ

Лучший ответ

У вас неопределенное поведение, поскольку f не инициализирован:

GeometrijskaFigura *f;
int x;
    
std::cin >> x;
    
f->setA(x); // UB: use uninitialized f.

Должно быть

int a;

std::cin >> a;

Jednakostranicni j;
j.setA(a);
std::cout << "Jednakostranicni-P: " << a.P() << " O: " << a.O() << std::endl;

Kvadrat k;
k.setA(a);
std::cout << "Kvadrat-P: " << k.P() << " O: " << k.O() << std::endl;

Krug krug;
krug.setA(a);
std::cout << "Krug-P: " << krug.P() << " O: " << krug.O() << std::endl;


0

Jarod42
7 Дек 2020 в 10:12

  1. Уважаемые гуру пожалуйста подскажите.
    Я с ардуино знаком на весьма любительском уровне.
    Я взял скетч из примеров из библиотеки Modbus-Master-Slave-for-Arduino-master.
    В этом примере данные из регистров мдбас слейв устройств считываются в массив
    uint16_t au16data[];
    В Модбас слейв в двух регистрах по 16 бит лежит одно значение float размером 32 бит
    то есть в двух ячейках uint16_t массива у меня сохраняться одно значение float размером 32 бит.
    Я планировал в скетче из двух uint16_t побитово перенести в переменную float 32 бита.
    Примерно так:

     uint16_t au16data[16] ;
      float volts  ;

     
      bitWrite(volts, 0, bitRead(au16data [1], 0));
      bitWrite(volts, 1, bitRead(au16data [1], 1));
      bitWrite(volts, 2, bitRead(au16data [1], 2));
      bitWrite(volts, 3, bitRead(au16data [1], 3));

     
      bitWrite(volts, 4, bitRead(au16data [2], 0));
      bitWrite(volts, 5, bitRead(au16data [2], 1));
      bitWrite(volts, 6, bitRead(au16data [2], 2));
      bitWrite(volts, 7, bitRead(au16data [2], 3));

    Но компилятор ругается.

    C:UsersVitalyAppDataLocalArduino15packagesarduinohardwareavr1.6.21coresarduino/Arduino.h:112:37: error:   in evaluation of ‘operator|=(float, long unsigned int)’
    #define bitSet(value, bit) ((value) |= (1UL << (bit)))
    C:UsersVitalyAppDataLocalArduino15packagesarduinohardwareavr1.6.21coresarduino/Arduino.h:114:52: note: in expansion of macro ‘bitSet’
    #define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
    C:UsersVitalyAppDataLocalTemparduino_modified_sketch_712994sketch_jun25c.ino:121:5: note: in expansion of macro ‘bitWrite’
         bitWrite(volts, 0, bitRead(au16data [1], 0));
    C:UsersVitalyAppDataLocalArduino15packagesarduinohardwareavr1.6.21coresarduino/Arduino.h:113:39: error: invalid operands of types ‘float’ and ‘long unsigned int’ to binary ‘operator&’
    #define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
    C:UsersVitalyAppDataLocalArduino15packagesarduinohardwareavr1.6.21coresarduino/Arduino.h:114:73: note: in expansion of macro ‘bitClear’
    #define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
    C:UsersVitalyAppDataLocalTemparduino_modified_sketch_712994sketch_jun25c.ino:121:5: note: in expansion of macro ‘bitWrite’
         bitWrite(volts, 0, bitRead(au16data [1], 0));
    C:UsersVitalyAppDataLocalArduino15packagesarduinohardwareavr1.6.21coresarduino/Arduino.h:113:39: error:   in evaluation of ‘operator&=(float, long unsigned int)’
    #define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
    C:UsersVitalyAppDataLocalArduino15packagesarduinohardwareavr1.6.21coresarduino/Arduino.h:114:73: note: in expansion of macro ‘bitClear’
    #define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
    C:UsersVitalyAppDataLocalTemparduino_modified_sketch_712994sketch_jun25c.ino:121:5: note: in expansion of macro ‘bitWrite’
         bitWrite(volts, 0, bitRead(au16data [1], 0));

    Встречал в инете обьяснение этому, но моих знаний не хватило понять это, там все была на СИ++.
    Пожалуйста подскажите, как в моем случае должен выглядеть код.
    Просьба сильно не пинать.

  2. bitwrite не работает с плавающей точкой.
    тебе надо использовать union сначала, чтоб конвертировать float в 2 int-а.

    union IntConvert {
      int   IntValues[2];
      float FloatValue;
    }

    и потом засовывать int-ы в массив, а забирать оттуда float целиком. И наоборот. И массив и float физически находятся по одному и тому же адресу памяти, разное только обращение к ней.
    Прочитай за union чонить.


    Andrey12 и Mitrandir нравится это.

  3. Последнее редактирование: 27 июн 2018

  4. Про union уже сказали. Ещё один путь — прямое копирование памяти:

    uint16_t from[2];
    float to;

    uint8_t* fromRead = (uint8_t*) from;
    uint8_t* toWrite = (uint8_t*) &to;

    memcpy(toWrite,fromRead,4); // копируем 4 байта

    Но! Это не всегда корректно, хотя бы из-за порядка следования байт. И вообще — желание из двух целых скопировать во float — кмк, сигнализирует о том, что ТС не совсем понимает, что нужно. На примере: допустим, в одном uint16_t содержится значение температуры в целых, во втором — в десятитысячных долях. Тогда конвертируется это во float довольно просто:

    uint16_t tempWhole = 12;
    uint16_t tempFract = 1234;

    float result = tempWhole;
    result *= 10000.0;
    result += tempFract;
    result /= 10000.0;

  5. Вот, для демонстрации безумства первого подхода (прямое копирование) и корректности работы второго — набросал тут: http://cpp.sh/ — небольшую программку:

    // Example program
    #include <iostream>
    #include <string>
    #include <cstring>

    int main()
    {
        uint16_t from[2] = {56,1234};
        float to;

        uint8_t* fromRead = (uint8_t*) from;
        uint8_t* toWrite = (uint8_t*) &to;

        memcpy(toWrite,fromRead,4); // копируем 4 байта  

       
      std::cout << to << «n«;

     
      uint16_t tempWhole = 56;
      uint16_t tempFract = 1234;

     
      float result = tempWhole;
      result *= 10000.0;
      result += tempFract;
      result /= 10000.0;

     
      std::cout << result << «n«;
    }

    Вывод программы:

  6. А были какие-то сомнения ? :)

  7. а нельзя ли так:

    uint16_t a,b; //2 половинки числа
    uint32_t x; //временная переменная
    float32_t y; //результат
    x=a;
    x=x<<16;
    x=x+b;
    y=(float32_t)x;

    Чую, я не понял задачу.

  8. Нет, это для демонстрации ТС ;)

  9. Вот код:

    // Example program
    #include <iostream>
    #include <string>

    int main()
    {
    uint16_t a = 56,b=1234; //2 половинки числа
    uint32_t x; //временная переменная
    float y; //результат
    x=a;
    x=x<<16;
    x=x+b;
    y=(float)x;
      std::cout << y;

    }

    Тестировал здесь: http://cpp.sh/ Вывод:

    Не очень похоже на 56.1234, не находите? ;)

  10. На 8-ми битке такое делать нельзя. Да и зачем?

  11. В каком месте такое нельзя сделать на восьмибитке? Вывод в поток — дык это не основа алгоритма, это просто демонстрация результатов, не более того. Остальное — вполне валидный код на С++, который ОБЯЗАН компилироваться любым современным компилятором.

  12. Огромное спасибо всем откликнувшимся за подсказки, кажется победил:

    int16_t au16data[]={17260, 0, 17259, 52429 };// 236.00 and 235.8
    float* ptr_recData;
    uint8_t numPar =0;   // номер параметра из массива
    float volts =0 ;
    int16_t temp[2];

    void setup() {
    Serial.begin(9600);
    ptr_recData = (float*)(&temp[0]) ;  // получаем адрес переменной
    }

    void loop() {

    temp [1] = au16data[(numPar*2)];
    temp [0] = au16data[(numPar*2)+1];
    volts =*ptr_recData;

    Serial.println(temp [0]);
    Serial.println(temp [1]);
    Serial.println(volts,8);

    Serial.println(«_»);

    ++numPar*2;
    temp [1] = au16data[(numPar*2)];
    temp [0] = au16data[(numPar*2)+1];
    volts =*ptr_recData;

    Serial.println(temp [0]);
    Serial.println(temp [1]);
    Serial.println(volts,8);
    Serial.println(«__________»);
    delay(2000);
    }

  13. плавающая запятая для чего? Вывод на дисплей? Можно отдельно выводить целую и отдельно дробную. АЛУ АВР-ок и так убогое, а вы ему ещё и плавающую запятую….

  14. Ты болеешь? Я ТС отвечал, и приводил только как ПРИМЕР. Что ТС там делает — хз, и мне пох. Не болей.

  15. Ну он же у него одни флоаты, да ещё и глобальные зачем-то. Ну ты прав — конкурентов не надо растить — без работы останешься.
    Ыыыы с такими горе программистами конкуренции не будет НИКОГДА. Так что я спокоен)))

Понравилась статья? Поделить с друзьями:
  • Error invalid number of arguments for encryption
  • Error invalid new expression of abstract class type
  • Error invalid module instantiation
  • Error invalid method declaration return type required java
  • Error invalid mailbox перевод