+ 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 Answers
+ 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
5th Apr 2022, 5:05 PM
Jayakrishna šŸ‡®šŸ‡³