2016-12-06 134 views
0

程序應從鍵盤讀取n個電阻和電壓,然後計算等效電阻和電流。 我的問題是,它僅基於最後輸入的阻力進行計算。 是否可以在函數內部聲明一個方法?或者我應該放棄這個不切實際的徹底辦法方法聲明問題

#include "stdafx.h" 
#include<iostream> 
#include<conio.h> 

using namespace std; 

class rez { 
    float r; 
public: 
    void set(int n); 
    float val() { return r; } 
}; 

void rez :: set(int n) {   //n is the number of resistances 
    int i; 
    for (i = 1; i <= n; i++) { 

     cout << "R" << i << "="; 
     cin >> r; 
    } 

} 

float serie(rez r1,int n) 
{ 
    float s=0; 
    int i; 
    for (i = 1; i <= n; i++) 
    { 
     s = s+ r1.val(); 
    } 
    return s; 
} 

float para(rez r1, int n) 
{ 
    float s = 0; 
    int i; 
    for (i = 1; i <= n; i++) 
    { 
     s = s + (1/r1.val()); 
    } 
    return 1/s; 
} 


int main() 
{ 
    char c, k = 'y'; // 'c' selects series or para 
    rez r1;    
    int n; 
    cout << "number of resis:"; 
    cin >> n; 
    cout << endl; 
    while (k != 'q') 
    { 
      r1.set(n); 
      float i, u; 
      cout << "\n Vdc= "; 
      cin >> u; 
      cout << endl; 

     cout << "series or para(s/p)?"<<endl; 
     cin >> c; 
     switch (c) 
     { 
     case('s'):cout <<"\n equiv resistance = "<< serie(r1,n)<<endl; 
      i = u/serie(r1, n); 
      cout << "curr i = " << i << " amp"; 
      break; 
     case('p'):cout << "\n equiv res = " << para(r1, n)<<endl; 
      i = u/para(r1, n); 
      cout << "cur i = " << i << " amp"; 
      break; 
     } 



     cout <<endl<< "\n another set?(y/q)?"<<endl; 
     cin >> k; 

    } 
    return 0; 
} 
+0

「是否有可能來聲明函數裏面的方法?」不,謝天謝地,「functionception」(我剛剛創造的一個術語)在C++中不受支持。 – George

回答

1

這是因爲當你在閱讀的電阻你每次不增加總電阻設定的總電阻的值。

void rez :: set(int n) {   //n is the number of resistances 
    int i; 
    for (i = 1; i <= n; i++) { 

     cout << "R" << i << "="; 
     cin >> r; // <- this sets the value of r, it does not add to it 
    } 

} 

爲了解決這個問題,你應該創建一個臨時變量來存儲輸入電阻,然後將其添加到總電阻

void rez :: set(int n) 
{ 
    int i; 
    for (i = 1; i <= n; i++) 
    { 
     float input; 
     cout << "R" << i << "="; 
     cin >> input; 
     r += input; 

    } 
} 
+0

'input'應該有'float'類型,而不是'int'。 –