Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error message displaying as "expression must have integral or enum type" in c++

Tags:

c++

I have the following code and I am getting the error at this equation:

v=p*(1+r)^n.

Please help me to find the reason for this error.

# include <iostream>
# include <limits>

using namespace std;

int main()
{
    float v,p,r;
    int n;

    cout<<"Enter value of p:";
    cin>>p;
    cout<<"Enter value of r:";
    cin>>r;
    cout<<"Enter value of n:";
    cin>>n;

    v=(p)*(1+r)^n; // here i am getting error message as "expression must have integral or enum type"

    cout<<"V="<<v;

    std::cin.ignore();
    std::cin.get(); 
}
like image 862
user3027039 Avatar asked Dec 06 '22 03:12

user3027039


2 Answers

C++11 5.12 - Bitwise exclusive OR operator

exclusive-or-expression: and-expression exclusive-or-expression ˆ and-expression 1 The usual arithmetic conversions are performed; the result is the bitwise exclusive OR function of the operands. The operator applies only to integral or unscoped enumeration operands.


If you want to compute v=(p)*(1+r)n, you need to change

v=(p)*(1+r)^n;

to

v = p * powf(1+r, n); // powf: exponential math operator in C++

In C++, ^ is XOR (exclusive or) operator, e.g. a = 2 ^ 3; // a will be 1.

Check out here for more info.

like image 69
herohuyongtao Avatar answered Apr 12 '23 23:04

herohuyongtao


The problem is that ^ is not an exponential math operator in C++, instead it is a bitwise xor operation. Bitwise operations can only be done on integral / enum values.

If you want to raise a floating point to a specific power use the powf function

powf(p * (1 + r), n)

// Or possibly the following depending on how you want the
// precedence to shake out
p * powf(1 + r, n)
like image 24
JaredPar Avatar answered Apr 12 '23 22:04

JaredPar