Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
144 views
in Data Types and Operators by (32.9k points)
closed by

The following C++ code segment is a part of a program written by Smitha to find the average of 3 numbers. int a, b, c; float avg; 

cin>>a>>b>>c; 

avg=(a+b+c)/3; ‘ 

cout<<avg;,What will be the output if she inputs 1, 4 and 5? How can you correct it?

1 Answer

+1 vote
by (30.7k points)
selected by
 
Best answer

=(1 +4+5)/3 =10/3 =3.3333 Instead of this 3.3333 the output will be 3. This is because if both operands are integers an integer division will be occurred, that is the fractional part will be truncated. 

To get the correct out put do as follows 

case 1: int a,b,c; is replaced by float a,b,c; 

OR 

case 2: Replace (a+b+c)/3 by (a+b+c)/3.0; 

OR 

case 3: Type casting. Replace avg=(a+b+c)/3; by avg=(float)(a+b+c)/3;

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

...