Error invalid operands of types double and int to binary operator

After compiling the program I am getting below error invalid operands of types int and double to binary 'operator%' at line "newnum1 = two % (double)10.0;" Why is it so? #include #

After compiling the program I am getting below error

invalid operands of types int and double to binary 'operator%' at line 
"newnum1 = two % (double)10.0;"

Why is it so?

#include<iostream>
#include<math>
using namespace std;
int main()
{
    int num;
    double two = 1;
    double newnum, newnum1;
    newnum = newnum1 = 0;
    for(num = 1; num <= 50; num++)
    {

        two = two * 2;
    }
    newnum1 = two % (double)10.0;
    newnum = newnum + newnum1;
    cout << two << "n";
    return 0;
}

Deanie's user avatar

Deanie

2,3042 gold badges18 silver badges35 bronze badges

asked Feb 14, 2012 at 14:03

Rasmi Ranjan Nayak's user avatar

2

Because % is only defined for integer types. That’s the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the
operands of % shall have integral or enumeration type. […]

As Oli pointed out, you can use fmod(). Don’t forget to include math.h.

Aᴍɪʀ's user avatar

Aᴍɪʀ

7,5033 gold badges37 silver badges52 bronze badges

answered Feb 14, 2012 at 14:05

Luchian Grigore's user avatar

Luchian GrigoreLuchian Grigore

251k63 gold badges454 silver badges619 bronze badges

1

Because % only works with integer types. Perhaps you want to use fmod().

answered Feb 14, 2012 at 14:06

Oliver Charlesworth's user avatar

Yes. % operator is not defined for double type. Same is true for bitwise operators like «&,^,|,~,<<,>>» as well.

answered Jul 18, 2013 at 1:51

Amar's user avatar

I’m writing a program for my control structures class and I’m trying to compile it. The only error, at least the only error the compiler is picking up is saying invalid operands of types ‘double’ and ‘int’ to binary ‘operator%’. Most of the program isn’t included since it’s too long and doesn’t really pertain to this problem, at least I don’t believe.

double maxTotal, minTotal;

cin >> maxTotal >> minTotal;

int addCalc;

static_cast<int>(maxTotal);

if(maxTotal % 2 == 1)
     addCalc = minTotal;
else
     addCalc = 0;

asked Aug 4, 2013 at 1:22

user2649644's user avatar

user2649644user2649644

1241 gold badge2 silver badges11 bronze badges

Your static_cast isn’t doing anything. What you should be doing is:

if(static_cast<int>(maxTotal) % 2 == 1)

Variables in C++ cannot change types. Static cast returns the casted value it does not change the input variable’s type, so you have to use it directly or assign it.

int iMaxTotal = static_cast<int>(maxTotal);

if(iMaxTotal % 2 == 1)
    addCalc = minTotal;
else
    addCalc = 0;

This would work too.

answered Aug 4, 2013 at 1:26

Borgleader's user avatar

BorgleaderBorgleader

15.7k5 gold badges45 silver badges62 bronze badges

0

You should assign your cast to a variable otherwise it’s not doing anything. static_cast<int>(maxTotal) will return a value of type int

double maxTotal, minTotal;

cin >> maxTotal >> minTotal;

int addCalc;

int i_maxTotal = static_cast<int>(maxTotal);

if(i_maxTotal % 2 == 1)
        addCalc = minTotal;
else
        addCalc = 0;

answered Aug 4, 2013 at 1:28

Hna's user avatar

HnaHna

9968 silver badges16 bronze badges

0

Bukharov11

0 / 0 / 0

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

Сообщений: 46

1

18.04.2012, 15:41. Показов 43017. Ответов 8

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


В строке где If выдает вот эту ошибку 2 раза:
invalid operands of types ‘double’ and ‘int’ to binary ‘operator%’

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int i, S=0;
const int n=5;
double x[n], k;
cout<<"Input "<<n<<"number:n";
for (i=0; i<n; i++)
cin>>x[i];
k=0;
if ((x[i]% 5)==0&&(x[i]% 7)!=0)
{
for (i=0; i<n; i++)
k++;
S+=x[i];
}
cout<<"Кол-во искомых членов: "<<k<<endl;
cout<<"Их сумма: "<<S<<endl;
return 0;
}

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



0



DPS

40 / 39 / 19

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

Сообщений: 177

18.04.2012, 15:54

2

Операция %деления применима только к целым числам(int), а у тебя массив типа double.
Получается, ты делишь дробное на целое и хочешь получить остаток… Чтобы это работало, необходимо объявлять

C++
1
int x[n]



0



0 / 0 / 0

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

Сообщений: 46

18.04.2012, 16:02

 [ТС]

3

Исправил на Int.
Ошибка пропала но программа неправильно работает.
суть в том что она должна из n чисел выбрать те, которые делятся на 5 и не делятся 7.



0



1179 / 892 / 94

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

Сообщений: 2,461

18.04.2012, 16:09

4

А как оказалось так, что оператор проверяющий условие находится над циклом а не в нем. Как вообще такое могло скомпилироваться.



0



0 / 0 / 0

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

Сообщений: 46

18.04.2012, 16:13

 [ТС]

5

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

А как оказалось так, что оператор проверяющий условие находится над циклом а не в нем. Как вообще такое могло скомпилироваться.

Нас так учили.



0



DPS

40 / 39 / 19

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

Сообщений: 177

18.04.2012, 16:14

6

Так что ли?

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
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int i, S=0;
const int n=5;
int x[n]; 
int k=0;
cout<<"Input "<<n<<"number:n";
for (i=0; i<n; i++)
cin>>x[i];
 
 
for(i=0;i<n;i++)
{
    if ((x[i]% 5)==0 && (x[i]% 7)!=0)
    {
        k++;
        S+=x[i];
    }
}
 
cout<<"Кол-во искомых членов: "<<k<<endl;
cout<<"Их сумма: "<<S<<endl;
return 0;
}



1



Bukharov11

0 / 0 / 0

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

Сообщений: 46

18.04.2012, 16:17

 [ТС]

7

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

Так что ли?

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
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int i, S=0;
const int n=5;
int x[n]; 
int k=0;
cout<<"Input "<<n<<"number:n";
for (i=0; i<n; i++)
cin>>x[i];
 
 
for(i=0;i<n;i++)
{
    if ((x[i]% 5)==0 && (x[i]% 7)!=0)
    {
        k++;
        S+=x[i];
    }
}
 
cout<<"Кол-во искомых членов: "<<k<<endl;
cout<<"Их сумма: "<<S<<endl;
return 0;
}

Спасибо огромное. Всё получилось.
Не силен я в этом.. не силен.



0



1179 / 892 / 94

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

Сообщений: 2,461

18.04.2012, 16:27

8

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

Нас так учили.

В том то и дело, что не могли Вас так учить За Вас подправили уже конечно, но надеюсь Вы поняли ошибку.



0



0 / 0 / 0

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

Сообщений: 46

18.04.2012, 16:30

 [ТС]

9

Да понял) еще раз спасибо большое)



0



  • 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.

How to fix invalid operands c errorThe invalid operands to binary expression C++ error might occur when a variable or object is considered a function. Moreover, you might get the same error due to using the wrong types of operands with the operators. If you are still in the same confused state, then read further to find a detailed explanation.

By the end of this post, you’ll surely figure out the erroneous line in your code, understand the reason, and have the perfect solution.

Contents

  • Why Do Invalid Operands To Binary Expression C++ Error Occur?
    • – Most Vexing Parse
    • – Using Modulus With Variables of Double Data Type
    • – Using a Comparison Operator With External Class Objects
    • – Using a Comparison Operator With Operands That Can’t Be Compared
  • How To Fix Error Invalid Operands?
    • – Remove the Parenthesis Following the Variable Name
    • – Cast the Modulus Operands To Int
    • – Round the Function Output and Cast It To Int
    • – Overload the Comparison Operator Outside the Class
    • – Fix the Operands To Eliminate Invalid Operands To Binary Expression C++ Error
  • FAQ
    • – What Does the Error “Invalid” Operands To Binary >> (Double and Int) Tells?
  • Conclusion

Why Do Invalid Operands To Binary Expression C++ Error Occur?

The above error might be occurring due to the most vexing parse that indicates the interpretation of an object as a function call. Moreover, the invalid operands or the external operands throw the same error. You can read below the complete descriptions of the reasons that have been stated earlier:

– Most Vexing Parse

The most vexing parse tells you that the variable declaration or object creation was considered a function call. Hence, you will get the above error when you use the same variable later in your program as an operand.

You can understand the scenario by imagining that you have declared a variable but accidentally placed a parenthesis in front of it. Next, you’ve coded to store the input inside the same and now, you are trying to print it. Here, you will get the above error because C++ grammar considered the variable declaration as a function call.

The coding block for the above scenario has been attached below:

#include <iostream>
using namespace std;
int main()
{
int age();
cout << “Please enter your age here: “;
cin >> age;
cin.ignore();
cout << “Your age is: “<< age <<“n”;
cin.get();
}

– Using Modulus With Variables of Double Data Type

As shown in the error statement itself, the invalid operands cause the stated error. The most common situation depicting the given reason is when the modulus “%” is used with the operands of double data type. Know that you can use only integers with the modulus.

– Using a Comparison Operator With External Class Objects

You might get the said error while comparing the properties of external class objects.

Here is the code that depicts the above scenario:

#include <iostream>
using namespace std;
class Plant{
public:
int height;
};
int main(){
Plant a, b;
a.height = 20;
b.height = 25;
if(a != b){
// do something
}
}

– Using a Comparison Operator With Operands That Can’t Be Compared

Another reason for the invalid operands error can be comparing the operands that can’t be compared. Here, you can imagine comparing a float variable with the void. It will definitely throw the same error.

You can fix the invalid operands error by implementing one of the solutions shared below as per the erroneous code found in your program:

– Remove the Parenthesis Following the Variable Name

So, if you have confused the C++ compiler regarding the variable and it has interpreted the same as a function, then remove the parenthesis following the variable name. It will solve the issue.

– Cast the Modulus Operands To Int

You can cast the modulus operands to int data type to make the above error go away. Similarly, casting the operands according to the operator requirement will help you every time when you face the same error.

– Round the Function Output and Cast It To Int

If your binary expression that uses the modulus contains the function output as an operand, then it would be a better idea to round the output. Next, you can convert the same into int to make the expression work.

– Overload the Comparison Operator Outside the Class

Pointing towards the error caused while comparing the external class objects’ properties, you can solve the same by overloading the given operator. It will ensure that the operator is already aware of the required class.

Please look at the code shown above that uses the Plant class and then see here to solve the issue:

#include <iostream>
using namespace std;
class Plant{
public:
int height;
};
static bool operator!=(const Plant& obj1, const Plant& obj2) {
return obj1.height != obj2.height;
}
int main(){
Plant a, b;
a.height = 20;
b.height = 25;
if(a != b){
cout << “The heights aren’t the same.” << endl;
}
}

– Fix the Operands To Eliminate Invalid Operands To Binary Expression C++ Error

Double-check the operands that you are comparing and change them accordingly to solve the error.

FAQ

You can find more information in this section.

– What Does the Error “Invalid” Operands To Binary >> (Double and Int) Tells?

The “invalid” operands to binary >> (double and int) error shows up to tell you that you are using the “>>” operator with operands of double data type. Remember that you can use “>>” with the values of integer data type only.

Conclusion

Fixing the stated error in your code isn’t a big deal after learning about the above solutions. Here is the simplified list of the solutions to let you see the fixing processes through the broader side:

  • You can fix the above error by removing any syntax errors that confuse the C++ compiler between variables and functions
  • Casting and changing the operands as per the operator requirement can help you fix the above error
  • Overloading the operators can help you in using external class objects in binary expressions

Invalid operands c errorCertainly, the said error revolves around the invalidity of the operands. You should simply be careful while using the same to avoid the error.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

  • #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

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