Error invalid operands of types double and double to binary operator

I've been making a Height prediction calculator but i have been given an error when compiling #include #include using namespace std; int main() { int i = 0; do...

I’ve been making a Height prediction calculator but i have been given an error when compiling

#include <iostream>
#include <string>
using namespace std;

int main() {

  int i = 0;
  do {
    double mom;
    double dad;
    string boygirl;
    double fullboy = (mom * 13 / 12 + dad) / 2;
    double fullgirl = (dad + 12 / 13 + mom) / 2;
    double twsub = 12;
    double twsub2 = 12;

    cout << " nnWELCOME TO THE C++ HEIGHT PREDICTION PROGRAM";
    cout << "nn INPUT GENDER TO BEGIN boy/girl: ";
    cin >> boygirl;

    cout << "How tall is your mother in inches: ";
    cin >> mom;
    cout << "How tall is your father in inches: ";
    cin >> dad;

    if (boygirl == "boy") {
      cout << fullboy % twsub2 << "ft"
           << "is your estimated height";
    }

    else if (boygirl == "girl") {
      cout << fullgirl % twsub << "ft"
           << " is your estimated height";
    }

    ++i;
  } while (i < 10);
}

The error is

error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator%

It happens when it goes through these lines of code:

if (boygirl == "boy") {
    cout << fullboy % twsub2 << "ft" << "is your estimated height";
}

and

else if (boygirl == "girl") {
  cout << fullgirl % twsub << "ft" << " is your estimated height";
}

I was wondering if anybody could help me fix this error in my code

Thank you

t.niese's user avatar

t.niese

38.3k8 gold badges71 silver badges99 bronze badges

asked Nov 1, 2020 at 22:27

Jabescuber's user avatar

6

In C++ you can use modulos operator % only on integral types like int. For floating point types like double you can use a function std::fmod() which is provided by standard library:

std::cout << std::fmod( fullboy, twsub2 ) << "ft is your estimated height";

Note you have also issues with integer division in this code:

double fullgirl = (dad + 12 / 13 + mom) / 2;

it should be something like:

double fullgirl = (dad + 12.0 / 13.0 + mom) / 2.0;

though in this line you do not have such issue:

double fullboy = (mom * 13 / 12 + dad) / 2;

it is better to do it everywhere as a good habit to prevent errors. Details can be found here Why does this calculation (division) return a wrong result?

answered Nov 1, 2020 at 22:34

Slava's user avatar

SlavaSlava

43.1k1 gold badge45 silver badges87 bronze badges

while solving a question on hackerearth i got this error , i tried to find solution but everywhere this error occurs when 2 different datatypes are used as operands but in my case both the operands of sama data type, here is my full code

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    int arr[1000];
    int n;
    cin>>n;
    double ans=1;
    for(int i =0; i<n ;i++)
    {
        cin >> arr[i];
        ans=(ans*arr[i])%(pow(10,9)+7);
    }
    cout << ans;
    return 0;

}

asked Apr 2, 2017 at 10:20

zoyron's user avatar

0

What’s the expected output of 12.3 % 4.2 ?
If you have an answer for that, you also have to roll your own implementation, built in operator% works for integer types only.

If you are fine with that, but your arguments happen to be floating point values, round/floow/ceil/cast them. e.g:

static_cast<uint64_t>(double_value);

answered Apr 2, 2017 at 10:25

erenon's user avatar

erenonerenon

18.7k2 gold badges62 silver badges89 bronze badges

Module operator (i.e. operator%) is not defined for floating points, but for integers only.

As you declared ans as a double, your expression ans*arr[i] evaluates as a double. Changing it to int ans will have the erroneous statement to compile (actually returning the integer modulo).

answered Apr 2, 2017 at 10:24

Ad N's user avatar

Ad NAd N

7,6005 gold badges33 silver badges73 bronze badges

I have a few errors here that I am trying to clear. I am using Dev-C++ to build this program. Obviously I am new to this.

The errors I am receiving;

main.cpp: In function `int main(int, char**)’:
main.cpp:48: error: invalid operands of types `double’ and `<unknown type>’ to binary `operator*’
main.cpp:48: error: invalid operands of types `<unknown type>’ and `int’ to binary `operator^’
main.cpp:48: error: invalid operands of types `double’ and `double’ to binary `operator^’
make.exe: *** [main.o] Error 1

They all pretty much refer to the following;

int height = ((tangent*(angle)*distance))-((.5)*(g)*((distance^2)/((speed^2*(cos(angle)*(cos(angle)))))));

[u][i][b]Here is the rest of the program

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main(int argc, char *argv[])
{

cout << «This program will find the height that a basketball» << endl;
cout << «launched by a robot that is 10 meters from the backboard.» << endl;
cout << «The user will enter the initial speed and firing angle.» << endl;
cout << «The local acceleration of gravity is g = 9.81 m/s2.» << endl;
cout<< endl;

//Instruct the user to enter variables
double speed;
double angle;
cout << «Please enter the initial speed in m/s: «;
cin >> speed;
cout << endl;
cout << «Please enter the initial angle in degrees: «;
cin >> angle;
cout << endl;

//Formulas for conversions
{
double PI = 3.14159265359;
double degree = PI / 180.0;
double tangent = (angle)*(degree);
double g = 9.81;
int height = ((tangent*(angle)*distance))-((.5)*(g)*((distance^2)/((speed^2*(cos(angle)*(cos(angle)))))));

//Display the results
cout << endl;
cout << setfill(‘*’)<<setw(37)<<» «<<endl;
cout << right<<setw(11)<<» Output «<<setw(13)<<» «<<endl;
cout << setfill(‘*’)<<setw(37)<<» «<<endl;
cout << setw(3)<<» «<<setfill(‘ ‘) << right << setw(19) << setprecision(2) << «Distance = «;
cout << right << setw(7) << fixed << showpoint << «10.00» <<setfill(‘*’)<<setw(3)<<» «<<endl;
cout << setw(3)<<» «<<setfill(‘ ‘) << right << setw(19) << setprecision(2) << «Initial Speed = «;
cout << right << setw(7) << fixed << speed <<» «<<setw(3)<<setfill(‘*’)<<» «<<endl;
cout << setw(3)<<» «<<setfill(‘ ‘) << right << setw(19) << setprecision(2) << «Initial Angle = «;
cout << right << setw(7) << fixed <<angle <<» «<<setfill(‘*’)<<setw(3)<<» «<< endl;
cout << setw(3)<<» «<<setfill(‘ ‘) << right << setw(19) << setprecision(2) << «Height = «;
cout << right << setw(7) << fixed <<height<<» «<<setfill(‘*’)<<setw(3)<<» «<< endl;
cout << setfill(‘*’)<< setw(37)<<» «<<endl;
cout << setfill(‘*’)<< setw(37)<<» «<<endl;
cout << endl;
cout << endl;
cout << «You have received height of a basketball launched by a robot, 10 meters»<<endl;//reiterate the reason for the program
cout << «from the backboard at your given speed and angle.»<<endl;
cout << endl;
cout << endl;

system(«PAUSE»);
return EXIT_SUCCESS;
}}

First thing I would try is removing the ^ operator.

I’m guessing from your calculations that you’re expecting it to be an exponent, it’s not, it’s a bitwise ‘exclusive or’ operator.

EDIT: Obviously, I don’t mean completely remove it. I mean sub it for a simple * operator:

1
2
distance^2 // Change instances of this....
distance * distance // ... to this 

Last edited on

Yup I took that out and gave distance a value as it had not been defined and it worked. Thanks!

Tuh123

0 / 0 / 0

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

Сообщений: 8

1

22.03.2020, 14:00. Показов 2583. Ответов 1

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


Не пропускает функцию компилятор, выдает ошибку
[Error] invalid operands of types ‘double’ and ‘double’ 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
23
24
25
26
27
28
29
#include <iostream>
#include <cmath> 
#include <iomanip>
#define _USE_MATH_DEFINES
using namespace std;
 
double f(double x)
{
    double y;
    y = (4*x*cos(x/2)*sin(x/2))/(sqrt(x^2-x+10));
    return (y);
}
int main()
{
    double a=M_PI,b=-M_PI;
    int n;
    double INTGRL = 0.0;
    cout << a << "       "<< b<< endl;
    cout << f(a)<<endl;
    cout << f(b)<<endl;
    cin >> n;
    double h = double((b-a)/n);
    for (double x = a; x <=b; x+=h)
        INTGRL += f(x-h/n);
    INTGRL*=h;
 
    cout << INTGRL;
    return 0;
}

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



0



6574 / 4559 / 1843

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

Сообщений: 13,726

22.03.2020, 14:10

2

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

Решение

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

[Error] invalid operands of types ‘double’ and ‘double’ to binary ‘operator^’

^
^ — это не степень, это XOR. Сделай вместо x^2
x *x или pow(x, 2)



1



Константа с плавающей запятой 1. имеет тип double.

Подобные сообщения об ошибках, как данное

invalid operands to binary % (have ‘double’ and ‘long double’

связаны с тем, как компилятор C осуществляет преобразование операндов с плавающей запятой в выражениях. Например, компилятор может преобразовывать операнды с плавающей запятой к формату, диапазон значений которых и точность превышают соответствующие диапазон значений и точность исходного типа с плавающей запятой. Это делается для того, чтобы в процессе вычислений выражений и их составных подвыражений получать более точные результаты.

Из стандарта C (5.2.4.2.2 Characteristics of floating types <float.h>)

9 Except for assignment and cast (which remove all extra range and
precision), the values yielded by operators with floating operands and
values subject to the usual arithmetic conversions and of floating
constants are evaluated to a format whose range and precision may be
greater than required by the type
. The use of evaluation formats is
characterized by the implementation-defined value of
FLT_EVAL_METHOD:24)

-1 indeterminable; 0 evaluate all operations and constants just to the range
and precision of the type;

1 evaluate operations and constants of type float and double to the
range and precision of the double type, evaluate long double
operations and constants to the range and precision of the long double
type;

2 evaluate all operations and constants to the range and precision of
the long double type.

All other negative values for FLT_EVAL_METHOD characterize
implementation-defined behavior.

Если включить заголовок , где имя FLT_EVAL_METHOD определено, то можно получить следующий результат

#include <stdio.h>
#include <float.h>

int main(void) 
{
    printf( "%dn",  FLT_EVAL_METHOD );

    return 0;
}

Вывод на консоль:

2

Как следует из вышеприведенной цитаты из стандарта C это означает, что константы будут преобразованы к типу long double.

Если заголовочный файл <float.h> не включен, тем не менее, видимо, компилятор использует данную опцию по умолчанию для вычисления выражений с плавающей запятой.

  • Remove From My Forums
  • Вопрос

  • HI I’m leaning both C# and C++ at the same time(I got two books by the same author for both). I get this weird error with the Multiplicative Operator % with a char. What I found out is that in C++ string can’t be used in a switch statement because 
    C/C++ doesn’t really support strings the same way as C#. To overcome this I used a char but now I got a new error and I have no clue what to do. In my switch statement «case ‘%'» I get an error saying 

    error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator%’. I’m guessing that in C++ I also for some reason can’t use Multiplicative Operator % with two doubles,floats,int etc.

    What do I do?

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        double fnumb,snumb,answer;
        char op;
    
        cout << "Enter first number n";
        cin >> fnumb;
    
        cout << "Enter Operator: + - * / % n";
        cin >> op;
    
        cout << "Enter Second number n";
        cin >> snumb;
    
        switch(op)
        {
            case '+': answer = fnumb + snumb; cout << fnumb << op << snumb  << "=" << answer; break;
            case '-': answer = fnumb - snumb; cout << fnumb << op << snumb  << "=" << answer; break;
            case '*': answer = fnumb * snumb; cout << fnumb << op << snumb  << "=" << answer; break;
            case '/': answer = fnumb / snumb; cout << fnumb << op << snumb  << "=" << answer; break;
            case '%': answer = fnumb % snumb; cout << fnumb << op << snumb  << "=" << answer; break;
            default : break;
        }
    
    
        return 0;
    }

    • Изменено

      15 июля 2012 г. 23:12

Ответы

  • Firo Prochainezo wrote:

    error: invalid operands of types ‘double’ and ‘double’ to binary  ‘operator%’.

    % can only be used with two integers. It’s inaplicable to doubles. You  can use fmod() function to calculate floating point remainder.

    I’m guessing that in C++ I also for some reason
    can’t use Multiplicative Operator % with two doubles,floats,int etc.

    Yes with int, no with doubles or floats.


    Igor Tandetnik

    • Предложено в качестве ответа
      Renjith V Ramachandran
      16 июля 2012 г. 8:22
    • Помечено в качестве ответа
      Elegentin Xie
      20 июля 2012 г. 7:19

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

3

  1. #include<cstdlib>
  2. #include<iostream>
  3. #include<iomanip>
  4. #include<vector>
  5.    #include<fstream>
  6. using namespace std;
  7.  
  8. double sum(vector<double> x)
  9.  {
  10.     double total = 0.0; 
  11.     for (int i=0; i<x.size(); i++) {
  12.         total = total + x[i];  
  13.     }
  14.     return total;
  15. }
  16.  
  17.  
  18.  
  19. int main()
  20. { vector<double> numbers;
  21.     double number;
  22.  int n;
  23.     ifstream in(«data.txt»);
  24.     while(in>>number)
  25.     {numbers.push_back(number);      }
  26.      for(int i=0;i<numbers.size();i++) 
  27. n= numbers.size();    
  28.     double k=sum(numbers);
  29. double y;
  30.   y=k/n;
  31.  
  32.      cout<<«mean of the values is:»<<» «<<y<<endl;
  33.  
  34.  for(int i=0;i<numbers.size();i++) 
  35. { double m= ((numbers[i]-y)*(numbers[i]-y));
  36.      vector<double> digits;
  37.      double digit;
  38.      while(m>>digit)
  39.      {digits.push_back(digit);}
  40.      double f=sum(digits);
  41.      double w=f/n;  
  42. cout<<«variance of the values is:»<<w<<endl;}
  43.  

hmmm,trying to calculate variance from values in vectors.but keep getting error saying invalid operands of types `double’ and `double’ to binary `operator>>’ what does tt mean n what shld i do?

Sep 17 ’07
#1

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