2017-05-29 86 views
0

你好我試圖用頭文件錯誤在C++中使用頭文件

//#include <iostream> 
//#include <cmath> 
#include "formula.h" 
//using namespace std; 


int main() 
{ 
//double r1; 
//double r2; 
//double r3; 
//double combinedresistors; 
//double counter; 

cout << "Enter your first resistance value:"; 
cin >> r1; 
cout << "Enter your second resistance value:"; 
cin >> r2; 
cout << "Enter your third resistance value:"; 
cin >> r3; 

//combinedresistors = 1/((1/r1) + (1/r2) + (1/r3)); 

if (r1 == 0) 
    cout << "ERROR:You can't have your resistance(s) value be zero"; 
// counter = 1; 
else if (r2 == 0) 
    cout << "ERROR:You can't have your resistance(s) value be zero"; 
// counter = 1; 
else if (r3 == 0) 
    cout << "ERROR:You can't have your resistance(s) value be zero"; 
    // counter = 1; 
else 
    cout << "Your combined Resistance is:" << combinedresistors << endl; 

return 0; 
} 

這裏運行這段代碼是頭文件。這就是所謂的formula.h

//header file 
    #include <iostream> 
    #include <cmath> 
    #include <string> 

    using namespace std; 

    double combinedresistors; 
    double r1; 
    double r2; 
    double r3; 

    combinedresistors = 1/((1/r1) + (1/r2) + (1/r3)); 

我註釋掉在main.cpp中文件的部分,因爲我以爲我會不會需要他們,因爲他們是在頭文件。這是我得到的錯誤...

c:\work area\c++\lab3\formula.h(15): error C4430: missing type specifier - 
int assumed. Note: C++ does not support default-int 
c:\work area\c++\lab3\formula.h(15): error C2371: 'combinedresistors': 
redefinition; different basic types 
c:\work area\c++\lab3\formula.h(10): note: see declaration of 
'combinedresistors' 
.\Lab3.cpp(34): error C2088: '<<': illegal for class 

我已經嘗試了很多事情,並期待在互聯網上,並不能找到這些東西,所以我需要幫助。

謝謝。

+0

你如何期望'combinedresistors = 1 /((1/r1)+(1/r2)+(1/r3));'工作?這是無效的語法,這些變量都沒有初始化。 –

+0

r1,r2,r3是用戶輸入...此公式是查找總阻力的一般公式。 – jde

+0

你不能在方法/函數之外進行計算,並且以這種方式編寫計算不會使它成爲可以以任何方式調用的函數。在任何情況下,一個類之外的頭部中的變量定義是一個禁止的。 –

回答

0

您需要在某些功能中編寫combinedresistors = 1/((1/r1) + (1/r2) + (1/r3));。像,

double GetCombinedResistors() 
{ 
return 1/((1/r1) + (1/r2) + (1/r3)); 
} 

和使用,

cout << "Your combined Resistance is:" << GetCombinedResistors() << endl; 
+2

更好的是,爲函數製作'r1','r2','r3'參數,而不是使用全局變量。 –

+0

@DavidScarlett同意。至少OP應該首先理解語法。 –

+0

@jde哪個錯誤? –

0

我不是一個很好的CPP程序員,但你可以用這個嘗試:

//#include <cmath> 
#include "formula.h" 
//using namespace std; 


int main() 
{ 
double r1; 
double r2; 
double r3; 
double combinedresistors; 
double counter; 

cout << "Enter your first resistance value:"; 
cin >> r1; 
cout << "Enter your second resistance value:"; 
cin >> r2; 
cout << "Enter your third resistance value:"; 
cin >> r3; 

if (r1 == 0 || r2 == 0 || r3 == 0){ 
    cout << "ERROR:You can't have your resistance(s) value be zero"; 
} 
else{ 
    combinedresistors = 1/((1/r1) + (1/r2) + (1/r3)); 
    cout << "Your combined Resistance is:" << combinedresistors << endl; 
} 

return 0; 
} 
+0

這很好,但不是我在找的,對不起。 – jde

+0

如果我沒有弄錯,這幾乎是OP開始的地方。 – user4581301

-2

最好是有一個主要方法你頭文件。是否有可能保持變量聲明和執行沒有方法。只要檢查它。它可能會工作