错误:二进制'operator^' 'float'和'int'类型的操作数无效

Error: invalid operands of types 'float' and 'int' to binary 'operator^'

本文关键字:类型 int 无效 操作数 二进制 operator 错误 float      更新时间:2023-10-16

我将类型为"float"answers"int"的无效操作数错误转换为二进制"operator ^",我不知道如何修复

错误发生在最后一行中的函数f中

非常感谢任何帮助

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

x的数据类型为float。您已经对其应用了逻辑XOR运算符。XOR需要整数操作数。

不过我怀疑你在找指数。C++没有指数运算符。相反,试试这样的东西:

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

我假设你的意思是用exp(-(x*x))乘以(2/sqrt(3.14),但我没有看到乘法运算符。