+ 1

A problem in my c code

#include <stdio.h> int main() { int houses; int percentage; scanf("%d", &houses); percentage = (2/houses)*100; printf(" %d", percentage); return 0; •why does it prints for me 0 ?!

14th Jan 2022, 2:34 AM
Hodeni
8 Respuestas
+ 5
In C, a/b = 0 when a<b and a,b are integers. Try using floats instead
14th Jan 2022, 2:40 AM
Simba
Simba - avatar
+ 4
printf("%f",percentage); If you want to get an integer output, try using ceil() or floor() as you expected.
14th Jan 2022, 4:21 AM
Simba
Simba - avatar
0
What if i wanted only whole numbers in my output as percentage ?
14th Jan 2022, 3:09 AM
Hodeni
0
Simba #include <stdio.h> int main() { float houses; float percentage; scanf("%f", &houses); percentage = (2/houses)*100; printf(" %d", percentage); return 0; } Now when houses = 3 it gives me percentage=1. Why ?
14th Jan 2022, 3:12 AM
Hodeni
0
You may try typecast the division: percentage = (float)2/houses*100 don't forget to use "%f" instead of "%d" in printf() in the final answer
16th Jan 2022, 2:16 AM
Christina Ricci
Christina Ricci - avatar
0
I found two interesting options and both uses typecasting: Integer percentage: #include <stdio.h> int main(void) { int houses; int percentage; scanf("%d", &houses); percentage = (float)2/houses*100; printf("%d", percentage); } Float percentage: #include <stdio.h> int main(void) { int houses; float percentage; scanf("%d", &houses); percentage = (float)2/houses*100; printf("%f", percentage); } In the second option you need only to change type of percentage (float percentage) and of course use "%f" in final printf(). Tip: for typecast you must avoid round brackets ( ) see the code.
16th Jan 2022, 2:32 AM
Christina Ricci
Christina Ricci - avatar
0
If you prefer not use typecasting, define percentage as float and use 2.0 instead of 2 in the division. Hope I helped ;)
16th Jan 2022, 2:37 AM
Christina Ricci
Christina Ricci - avatar
0
Thankyou.🤝
25th Jan 2022, 2:39 AM
iam_Shivv
iam_Shivv - avatar