I have a question about Java programming practice.

Asked 2 years ago, Updated 2 years ago, 26 views

HW#2_1 Sum of 1 to n with limited maximum value

The user inputs the number max, and obtains a maximum n whose sum from 1 to n is less than the input max.

Ex) Enter a maximum value: 100 The sum from 1 to 13 is 91, not exceeding the maximum value of 100. Therefore, n = 13.

Currently, the code I made is (unfinished)

package zzz; import java.util.*; public class first

{ public static void main(String[] args) 
{Scanner a = new Scanner(System.in);
    System.out.print ("Enter the maximum value: ");
    int max = a.nextInt();
    int z=0;
    int b;
    for(int i=1;i<=b;i++)
    z=z+i;
    if(z<max);

    System.out.print(b);
    }

}

I think the price should come out like this, but only the error appears
Is it the wrong way at all?

java

2022-09-22 16:08

2 Answers

Why don't you change the middle factor of for to z <= max?

But the problem is unclear whether the sum of 1 to n is not more than max (hereinafter) or less than max.


2022-09-22 16:08

for (int i = 1; i < max; i++) {
   z += i;
   if (z >= max) {
     break;
   } } else {
      b = i;
   }
}

System.out.print(b);

I think this will work.

And please initialize int b = 0.


2022-09-22 16:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.