简体   繁体   中英

Possible loss of precision double

int leccs1 = q1+q2+r1+swhw1;
System.out.println("LecCS = "+ leccs1+ "/60");
int lecprelim = lcp+lcpo;
System.out.println("LecPrelim = "+ lecprelim+ "/100");
double x = 0.50;
int lecgrade = ((x * leccs1) + (x * lecprelim));
System.out.println("LecGrade = "+ lecgrade);



C:\FINALS OBE\OBE1\ICS112_1ISB_LecFinals_OBE.java:61: error: possible loss of precision
    int lecgrade = ((x * leccs1) + (x * lecprelim));
                                 ^
  required: int
  found:    double
1 error

Process completed.

I am trying to compute grade. The user enters the grades as input. I want x to be double not int.

change

   int lecgrade = ((x * leccs1) + (x * lecprelim));

to

double lecgrade = ((x * leccs1) + (x * lecprelim));

int grade=lecgrade.intValue();

or in a single line you can write

int lecgrade = ((x * leccs1) + (x * lecprelim)).intValue();

use intValue() to convert from double to int

check intValue()

What i came to know is you want lecgrade as an int you can do this by type casting

Try this,

int lecgrade =(int) ((x * leccs1) + (x * lecprelim));

If you need lecgrade to be of type int, you probably want to apply some rounding before casting, eg:

        double lecgrade = 1.9d;

        int result = (int) lecgrade;
        int resultRounded = (int) Math.round(lecgrade);

        System.out.println(result); // prints 1
        System.out.println(resultRounded); // prints 2

Please note that

  1. intValue() is not applicable to primitives, you'd have to box your value first
  2. intValue() may truncate your value instead of rounding it

      Double k = Double.valueOf(1.9d); System.out.println(k.intValue()); // prints 1 for me 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM