Home > Mobile >  How can I solve this if condition — I don't know where the problem is in this case?
How can I solve this if condition — I don't know where the problem is in this case?

Time:06-12

    float i, r1, r2, sum1, sum2; 
    char resistance[30];
    
    printf("what is the curent total: ");
    scanf("%f", &i);
     
    printf("what is the resistance1 and resistance2: ");
    scanf("%f%f", &r1, &r2);
    
    printf("what is the R you want to know there curren\n: ");
    printf("notes:write your choes in capital example R1,R2:");
    scanf("%s", resistance);
    
    sum1 = (r2 / r1   r1) * i;
    sum2 = (r1 / r1   r2) * i;
    
    if (strcmp(resistance, "R1") == 0) {
        printf("the current in this resistance is %f", sum1);
    } else if {
        printf("the current in this resistance is %f", sum2);
    }

CodePudding user response:

Your code fragment does not compile because there is an extra if after the else. You can test another condition in the else part with else if (condition) but this does not seem to be your intent.

Also note than the formulae are incorrect. Here is the math:

  1. V = i . R
  2. with 1 / R = 1/r1 1/r2
  3. and V = i1 . r1 = i2 . r2
  4. replacing R in 1): V = i . 1 / (1/r1 1/r2)
  5. replacing V: i1 . r1 = i / (1/r1 1/r2)
  6. reducing to common denominator: i1 . r1 = i / ((r2 r1) / (r1 * r2))
  7. simplifying: i1 . r1 = (i . r1 . r2) / (r2 r1)
  8. dividing by r1: i1 = (i . r2) / (r2 r1)
  9. same for i2: i2 = (i . r1) / (r2 r1)

Here is a modified version:

#include <stdio.h>
#include <string.h>

int main() {
    float i, r1, r2, i1, i2; 
    char resistance[30];
    
    printf("what is the total current: ");
    if (scanf("%f", &i) != 1)
        return 1;
     
    printf("what are the resistance1 and resistance2: ");
    if (scanf("%f%f", &r1, &r2) != 2)
        return 1;
    
    printf("what is the R you want to know there current\n: ");
    printf("note: write your choice in capitals example R1,R2: ");
    if (scanf(")s", resistance) != 1)
        return 1;
    
    i1 = i * r2 / (r1   r2);
    i2 = i * r1 / (r1   r2);
    
    if (strcmp(resistance, "R1") == 0) {
        printf("the current in resistance R1 is %f\n", i1);
    } else if (strcmp(resistance, "R2") == 0) {
        printf("the current in resistance R2 is %f\n", i2);
    } else {
        printf("choice must be R1 or R2\n");
    }
    return 0;
}
  •  Tags:  
  • c
  • Related