Why is it summing a long negative integer to zero????
Code Java:
import java.util.Scanner;
public class Exercise2_6M
{
public static void main(String[] args)
{
// Create a Scanner
Scanner input = new Scanner(System.in);
// Enter amount
System.out.print("Enter an integer:");
int integer = input.nextInt();
// Calculations
int rinteger = Math. abs (integer);
int sum = 0;
int i=0;
//loop through each digit (starting from the least significant) until the end of the number
while(rinteger / Math.pow(10,i) > 0)
{
sum+=getDigit(rinteger,i);
i++;
}
// Display results
System.out.println("Sum all digits in " + integer + " is " + sum);
}
public static int getDigit(int num, int power)
{
return (num % (int)Math.pow(10,power+1)) / (int)Math.pow(10,power);
}
}
Re: Why is it summing a long negative integer to zero????
Is this program built to find the sum of the digits? Or to find the sum of the digits up to the number?
Would 123 be... 1+2+3
or
Would 123 be... 1+2+3+4+5...+122+123
Re: Why is it summing a long negative integer to zero????
As far as i know, when you apply the power function, it crosses the limit of integer. And shows you the result after that.
You must take care of memory sizes provided to different data types.