-3

The Code is to simply display calculations of two numbers taken from user

import java.util.Scanner;
public class simple_Calculator {

    public static void main(String[] args) {
        Scanner in =new Scanner(System.in);

        System.out.println("Input First Number:");
        int num=in.nextInt();

        System.out.println("Input Second Number:");
        int num1=in.nextInt();

        int a,b,c,d;
        float e;
        a=num+num1;
        b=num-num1;
        c=num*num1;
        e=num/num1;
        d=num%num1;

        System.out.println("num"+"+"+"num2"+"="+a);

        System.out.println("num"+"-"+"num1"+"="+b);

        System.out.println("num"+"*"+"num1"+"="+c);

        System.out.println("num"+"/"+"num1"+"="+e);

        System.out.println("num"+"mod"+"num1"+"="+d);


    }

}

Look it is not correct of divide and modulus whats the problem can you help me to fix this

Harsh
  • 372
  • 2
  • 15

3 Answers3

0

When diving ints you lose accuracy. You should cast each operand to float or simply use floats in these operations. This is the way you can cast both operands to float:

float e = (float)sum1/(float)sum2;
Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21
0

With a Type Cast your code should work correct.

e = (float)num / (float)num1;
d = (int) ((float)num % (float)num1);

http://www.studytonight.com/java/type-casting-in-java

Fry123
  • 38
  • 4
0

Integers will simply truncate numbers after decimal point. It cannot be a decimal value and the division you are doing is of two int, so it simply discards the value after decimal point. Try this,

float x1 = (float)num;
float y1 = (float)num1;
float e = x1/y1;
Harsh
  • 372
  • 2
  • 15