You have a problem in the logic of your program. To begin with, nesting the conditional, when it should not be like that. Unless you do not understand what you are trying to do, the idea is to implement a structure if
- else if
- else
, which would be something like this
if (expresión)
{
Bloque de código;
}
else if(expresión)
{
Bloque de código;
}
else
{
Bloque de código;
}
Even eliminating the nesting the logic is not correct:
-
If I
is 0 the code of the if is executed regardless of the value of A
and V
.
-
If I
is not zero but v
is 0, what is inside the first else if
is executed regardless of the value of R
.
-
If I
e V
are zero but R
is not, the code of the second else if
is executed.
-
else
runs only if all variables are different from 0 .
This is not what you want, in synthesis you need to check which of the three variables is zero (which you want to calculate), if there are more than one that are unknown (or the resistance is negative) you can not calculate anything. This leaves us with three valid possibilities:
- i = 0 and a ≠ 0 and r > 0
- r = 0 and i ≠ 0 and r ≠ 0
- a = 0 and i ≠ 0 and r > 0
Note : the intensity and voltage may be negative, but not the resistance.
You need to do these three checks on your construction if- else if
. So that the else
is executed if none is fulfilled:
#include <stdio.h>
#include <conio.h>
int main (void)
{
float i = 0, v = 0, r = 0;
printf("calculadora ley de ohm \t\t(Si no tienes un valor pon 0)");
printf("\n\nIntensidad:\t 0\nVoltaje:\t 0\nResistencia:\t 0\n\n");
printf("Intensidad? \n");
scanf("%f", &i);
printf("Voltaje? \n");
scanf("%f", &v);
printf("Resistencia? \n");
scanf("%f", &r);
if (i==0 && v!=0 && r>0)
{
i = v/r;
printf("\n\nIntensidad:\t %.2f\nVoltaje:\t %.2f\nResistencia:\t %.2f\n", i, v, r);
}
else if (v==0 && i!=0 && r>0)
{
v = i*r;
printf("\n\nIntensidad:\t %.2f\nVoltaje:\t %.2f\nResistencia:\t %.2f\n", i, v, r);
}
else if (r==0 && v!=0 && i!=0)
{
r = v/i;
printf("\n\nIntensidad:\t %.2f\nVoltaje:\t %.2f\nResistencia:\t %.2f\n", i, v, r);
}
else
printf("\nLo siento, no puedo calcularlo.");
getch();
return 0;
}
Exit examples :
law of ohm calculator (If you do not have a value put 0)
Intensidad: 0
Voltaje: 0
Resistencia: 0
Intensidad?
8
Voltaje?
230
Resistencia?
0
Intensidad: 8.00
Voltaje: 230.00
Resistencia: 28.75
calculadora ley de ohm (Si no tienes un valor pon 0)
Intensidad: 0
Voltaje: 0
Resistencia: 0
Intensidad?
0
Voltaje?
230
Resistencia?
0
Lo siento, no puedo calcularlo.