Monday, April 23, 2018

Class X (ICSE) Explicit conversion explanation through example



CLASS - X (ICSE)
COMPUTER  APPLICATION


Concept to remember: In case of division always remember that if numerator and denominator are integer then answer would be without fractional part. 

But either numerator or denominator is real constant then it will divide thoroughly by giving the fractional part also. 

Example: 3/4 = 0
                3.0/4 = 0.75
                3/4.0 = 0.75 
                3.0/4.0 = 0.75

//Program to calculate average of four numbers such that if users enter 2, 3, 4, 5 then the result will be 3.5
package com.mohan;

class Pattern
{
      public static void main(String[] args) {
                 int num1 = 2 ,num2 = 3, num3 = 4, num4 = 5;
                 float avg;
                 avg=(float)(num1+num2+num3+num4)/4;  //Explicit conversion

            System.out.println(avg);
      }

}


Output: 3.5

Explanation: As you know program runs line by line,
                  int num1 = 2 ,num2 = 3, num3 = 4, num4 = 5; this line will store a number 2,3,4,5 in variable num1,num2,num3 and num4 respectively.


                 avg=(float)(num1+num2+num3+num4)/4; In this line sum of four numbers is dividing by 4.
To divide it completely we need to convert either numerator or denominator with a fractional part such as 4.0 but in this line we are not writing 4.0 so we are converting the numerator into real constant by converting it explicitly.


Hence in the above program if you wants to divide thoroughly, you can write 
                  avg=(float)(num1+num2+num3+num4)/4;  //In this you are converting numerator into real constant
                            or
                  avg=(num1+num2+num3+num4)/4.0;       // In this denominator is in real constant

But,
 if you are writing it as                   avg=(num1+num2+num3+num4)/4.0;   
 then output will be 3.0 because avg is of float type


No comments:

Post a Comment