2016-12-06 76 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'。 –