2016-03-24 99 views
0

我得到了類型'float'和'int'的錯誤無效操作數到二進制'運算符^',我不是知道如何解決它錯誤:類型'浮動'和'int'到二進制'運算符'的無效操作數''

在函數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)); 
} 
+1

'exp(-x^2)'不符合你的想法。 – drescherjm

回答

2

x的數據類型爲float。您已將邏輯XOR運算符應用於它。 XOR需要整數操作數。

雖然我懷疑你正在尋找一個指數。 C++沒有指數運算符。相反,嘗試這樣的事:

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

我假設你的意思(2/sqrt(3.14)exp(-(x*x)),但我沒有看到一個乘法運算符那裏。

+0

說明:'^'是異或運算符,而不是指數運算符。 – Logicrat

+1

值得一提的是「pow」。 –

+0

@ChristianHackl好點。 'pow(x,n)'將返回* x *到* n *次方。就個人而言,我從不使用'pow()'作爲方塊,但我同意很好意識到這一點。 – Logicrat

相關問題