Programming Noob - 1 year ago 52
C Question

# Not calculating correctly

So guys, I'm very new to programming and the C language, just learning it for fun :) So the Currnt is calculating quite right, it can calculate 4/2 but when I try 6/15 it just answers 0, any idea why?

``````    #include <stdio.h>
int main () {

int Volt,Resst;
float Currnt;

printf("Enter the value of resistor:");
scanf("%d",&Resst);
printf("Enter the voltage of power supply:");
scanf("%d",&Volt);
if (Volt > 10)
printf("The voltage is too big\n");
else if (0 > Volt)
printf("Not a valid input\n");
else {
Currnt=Volt/Resst;
printf("The current is %.2f A\n",Currnt);
}

}
``````

Answer Source

If an if/else statement block contains more than 1 command (like your last else branch), you need to use curly braces:

``````if (Volt > 10)
printf("The voltage is too big");
else if (0 > Volt)
printf("Not a valid input");
else {
Current=Volt/Rest;
printf("...");
}
``````

To avoid errors like this, it is considered best practice to always use curly braces, even if there is only one command in a block:

``````if (Volt > 10) {
printf("The voltage is too big");
}
else if (0 > Volt) {
printf("Not a valid input");
}
else {
Current=Volt/Rest;
printf("...");
}
``````

UPDATE

In C/C++ the type of the result of an expression (division in your case) is solely based on the type of the variables in it. In your case the expression is `int / int`, so the result will be considered `int` - the type of the variable where you store it does not matter. The solution is to explicitly cast at least one of the expression variables to `float`:

``````Currnt = (float)Volt/Resst;
``````

or

``````Currnt = Volt/(float)Resst;
``````

or

``````Currnt = (float)Volt/(float)Resst;
``````