c++ - 方法声明问题

标签 c++ function class

程序应该从键盘读取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;
}

最佳答案

这是因为当您读入电阻时,您每次都在设置总电阻的值,而不是增加总电阻。

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;

    }
}

关于c++ - 方法声明问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41006229/

相关文章:

python - 如何使用 SWIG 让 python 切片与我的 c++ 数组类一起工作

Javascript 给了我与我预期不同的值(value)

python - 函数在单独的实例中以不同的方式运行-python

c++ - 在类中实例化类

ruby - 在继承方面如何为ruby中的类定义 "<"?

c++ - 带有初始化变量和负数的 memcpy

c++枚举类整数不适用于数组下标

c++ - 使用 SFML 在屏幕上居中文本

java - 返回原始开始位置,无需退出应用程序并再次打开它

mysql - 使用PHP脚本备份数据库而不使用Mysqldump,有推荐的CLASS吗?