阻力计算器

时间:2016-02-24 19:49:45

标签: c

所以我正在尝试构建一个程序来计算并联或串联电路的电阻。计算并联电阻的公式为:

1/R_t = (1/R_1) + (1/R_2) + (1/R_n)...

我遇到的问题是程序输出“-1。#QNAN0”进行并联电阻计算。有什么建议?

#include <stdio.h>

int main() {

int n, choice, i;
char sel;
float res_tot, inv_res_tot;

printf("This is a program that calculates resistance.\n");

do{
    printf("Enter 1 for parallel or 2 for series: ");
    scanf("%d", &choice);

    printf("How many resistors are there: ");
    scanf("%d", &n);
    printf("\n");

    double r[n];

    for(i=0; i<n; i++) {
        printf("Resistor %d: ", i+1);
        scanf("%lf", &r[i]);
    }

    if(choice==1) {
        for(i=0; i<n; i++){
            inv_res_tot+=(1/r[i]);
        }

        res_tot=(1/inv_res_tot);
    }   

    else if(choice==2) {
        for(i=0; i<n; i++) {
            res_tot+=r[i];
        }   
    }

    printf("\nThe total resistance is: %f Ohms\n", res_tot);

    printf("\nWould you like to calculate another(y/n): ");
    getchar();
    scanf("%c", &sel);

} while(sel=='Y' || sel=='y');



return(0);  
}

1 个答案:

答案 0 :(得分:0)

您没有初始化inv_res_totres_tot

您应该在while loop的每次迭代中执行此操作。

http://ideone.com/Dgv4kJ