错误消息在 C++ 中显示为"expression must have integral or enum type"

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

本文关键字:have must integral or type enum expression 错误 C++ 显示 消息      更新时间:2023-10-16

我有以下代码,我在这个等式中得到错误:

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

请帮助我找到此错误的原因。

# 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(); 
}

C++11 5.12 - 按位独占 OR 运算符

独占或表达式: 和表达 独占或表达式 ˆ 和表达式 1 执行通常的算术转换;结果是按位 操作数的独占 OR 函数。运算符仅适用于积分 或无作用域枚举操作数。


如果要计算 v=(p)*(1+r)n,则需要更改

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

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

C++中,^XOR(独占或)运算符,例如 a = 2 ^ 3; // a will be 1 .

查看此处了解更多信息。

问题是^不是C++的指数数学运算符,而是按位异或运算。 按位运算只能对整数/枚举值进行。

如果要将浮点数提高到特定幂,请使用 powf 函数

powf(p * (1 + r), n)
// Or possibly the following depending on how you want the
// precedence to shake out
p * powf(1 + r, n)

位独占 OR 运算符 ^

仅适用于整型或无作用域枚举操作数

(C++标准)

相关文章: