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?
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.
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.
710 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
549 PHP ssh2_scp_send fails to send files as intended
537 Uncaught (inpromise) Error on Electron: An object could not be cloned
548 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
547 Who developed the "avformat-59.dll" that comes with FFmpeg?
© 2024 OneMinuteCode. All rights reserved.