+ 1
Stuck in java
In the following code, which i designed to calculate the sum of whole numbers. Whenever I enter a number greater than or equal to 10000000, the answer comes in negative https://code.sololearn.com/clR4yAfuXQer/?ref=app
4 Antworten
+ 3
use long instead of int to deal with larger values
+ 2
long sum is enough + you can check overflow this way:
int sum=0, x=0; // int for this test, long is better
try {
for (x = 0 ; x <=new1 ; ++x){
// sum = sum + x ;
sum = Math.addExact(sum, x);
}
} catch (ArithmeticException e) {
System.out.println("Numeric overflow" +" x = " +x);
}
System.out.println("sum = "+sum);
+ 1
int data type has a limit(2^31-1)
All data types have a limit
So for huge numbers use long or double data type