非常感谢您花时间,我在插入变量m的过程中不断得到一个无限循环,任何人都可以请看看谢谢。
public static void main program7_2(String args [])
{
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the first number: ");
int n = sc.nextInt();
while((n%2)== 0)
{
System.out.println("The number you entered is incorrect please enter an odd number:");
n = sc.nextInt();
}
System.out.println("Please enter the second number: ");
int m = sc.nextInt();
while((m%2)== 0)
{
System.out.println("The number you entered is incorrect please enter an odd number:");
m = sc.nextInt();
}
int sum =0;
for (int i = n; n<=m; i++)
{
if ((i%2) != 0)
sum = sum + i;
}
System.out.println("Sum of the numbers between "+n+ " and " +m+": " + sum);
}
程序的问题是输入2个奇数并得到奇数之和
谢谢和问候
答案 0 :(得分:3)
使用n<=m
代替i<=m
,而不是i
,而不是n
答案 1 :(得分:1)
这是错误:
for (int i = n; n<=m; i++) /* terminating condition "n<=m" is never met here */
{
if ((i%2) != 0)
sum = sum + i;
}
为什么:此循环会增加i
,但终止条件为n<=m
,永远不会满足....所以i<n
或{{1}哪个适合你终止条件!!
答案 2 :(得分:0)
如果你想获得这两者之间的数字总和
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number: ");
int n = sc.nextInt();
while ((n % 2) == 0) {
System.out.println("The number you entered is incorrect please enter an odd number:");
n = sc.nextInt();
}
System.out.println("Please enter the second number: ");
int m = sc.nextInt();
while ((m % 2) == 0) {
System.out.println("The number you entered is incorrect please enter an odd number:");
m = sc.nextInt();
}
int sum= 0;
for (int i = n; i <= m; i++) {
sum = sum + i;
}
System.out.println("Sum of the numbers between " + n + " and " + m + ": " + sum);
}
}