I need to display all even numbers for that are less than a specific number. Those numbers are random generated between a range. Here's the assignment:
Write a program that prompts the user to enter an integer (n). Your program generates then, another random integer (max) that reaches at most 10 * n. So if n entered was 5, the number generated (max) should be between 5 and 50 (5*10). This program displays the sum of all even numbers less than (max). Your program stops at the first sum value reached greater than max. Display its value.
What I have done so far:
Scanner s = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = s.nextInt();
int most = (10 * n) - (n+1);
int max = (int)( n + Math.random() * most);
System.out.println("Maximum generated is: "+ max);
for(int i = 2 ; i < max; i+=2) {
int num = max/i;
if(num % 2 == 0) {
System.out.print("number is "+ num);
}
}
Sample run:
Enter an integer: 5
Maximum generated is: 45
Sum of (6 8 10 12) = 50 //we stopped because 50 is the first sum greater
//than max
What's wrong?
I think your logic should like this,
int sum = 0;
int i = 2;
while (i<max) {
sum+=i;
if (sum > max) {
break;
}
i+=2;
}
System.out.print("Value=" + sum);
You can do this:
for(int i=0; i<max; i=i+2){
sum+=i;
}
System.out.println(sum); It does however sound like there might be an even faster dirrect mathametical formula for fonding the sum of all even numbers bellow a certain number but that's a question for another stack exchange.
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.