+ 2

Why both of them have different output ?

1️⃣ int main() { int a, b, c, sum; float avg; a=1; b=6; c=3; sum=a+b+c; avg=sum/3; cout<<"Sum = "<<sum<<endl; cout<<"Average = "<<avg; return 0; } 2️⃣ int main() { int a, b, c; float sum, avg; a=1; b=6; c=3; sum=a+b+c; avg=sum/3; cout<<"Sum = "<<sum<<endl; cout<<"Average = "<<avg; return 0; } Why the 1st code prints the integral value of Average and the 2nd one prints the floating value ❓❔

5th Apr 2022, 11:20 AM
Jainil Raval
Jainil Raval - avatar
5 Respuestas
+ 4
int/int results int double/int => double int/double => double double/double => double Values are upcasted to higher types in calculations and result is casted back to destination types.. In first, sum is int type so int/int return int data only.. While second sum is of float data type so float/int returns float data type value... Hope it helps..
5th Apr 2022, 11:24 AM
Jayakrishna 🇮🇳
+ 3
Jayakrishna🇮🇳 Ok got it.... Thanks 🙏
5th Apr 2022, 5:02 PM
Jainil Raval
Jainil Raval - avatar
+ 3
A͢J Got it... Thanks
5th Apr 2022, 5:03 PM
Jainil Raval
Jainil Raval - avatar
+ 1
Jainil Raval 🇮🇳 sum variable is declared as float so sum = 1 + 6 + 3 = 10.0 And 10.0 / 3 gives float value
5th Apr 2022, 2:04 PM
A͢J
A͢J - avatar
+ 1
You're welcomeJainil Raval 🇮🇳
5th Apr 2022, 5:05 PM
Jayakrishna 🇮🇳