2016-02-24 145 views
0

所以我試圖建立一個程序來計算並聯或串聯電路的電阻。計算並聯電阻的公式爲:電阻計算器

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); 
} 
+0

什麼是你的輸入和預期的輸出? – dbush

+0

你真的不需要將值存儲到數組中,你可以即時計算它。 –

+0

嘗試初始化'inv_res_tot'。和'n'。奇怪的未初始化的值可以肯定地解釋你奇怪的結果。 –

回答