public static void main(String[] args) {
int maxNum, sum, counter; // input value
Scanner input = new Scanner(System.in);
System.out.print("How many odd numbers should I add up?: ");
maxNum = input.nextInt();
sum = 0;
for (counter = 1; counter < maxNum; counter++)
{
sum = counter + maxNum;
}
System.out.println("\n" + "The sum of the odd numbers between 1 and " + maxNum + " is: " + sum);
}
根据具体的代码,它应该只通过奇数来解决加法问题。
现在我尝试了一个数字,5,根据我的输出:
How many odd numbers should I add up?: 5
The sum of the odd numbers between 1 and 5 is: 9
有效。但是当我尝试用另一个数字10时,出了点问题:
How many odd numbers should I add up?: 10
The sum of the odd numbers between 1 and 10 is: 19
我知道我的数学问题,但是从1到10的奇数不能加到19,它总计达到25。
代码有问题。任何人都可以找出问题所在吗?
答案 0 :(得分:0)
for (counter = 1; counter < maxNum; counter+=2)
{
sum += counter;
}
您添加的号码错误。
答案 1 :(得分:0)
您的for
循环正在添加错误的号码,需要跳过其他所有号码。
for (counter = 1; counter <= maxNum; counter+=2)
{
sum += counter;
}
输出(如果我们添加调试):
counter = 1,sum = 1
counter = 3,sum = 4
counter = 5,sum = 9
counter = 7,sum = 16
counter = 9,sum = 25
另一种方法是使用while
循环:
counter = 1;
while(counter < maxNum)
{
if (counter % 2 != 0)
{
sum += counter;
}
counter++;
}
输出(如果我们添加调试):
counter = 1,sum = 1
counter = 3,sum = 4
counter = 5,sum = 9
counter = 7,sum = 16
counter = 9,sum = 25
答案 2 :(得分:0)
将此代码用于循环内部。
if(counter%2==1){
sum=sum+counter;
答案 3 :(得分:0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Part_C_6
{
class Program
{
static void Main(string[] args)
{
int n;
Console.WriteLine("Enter N");
n = int.Parse(Console.ReadLine());
Console.WriteLine(odd(n));
}
public static int odd(int x)
{
int j,ans=0;
for (j = 1; j < x; j+=2)
{
ans = ans + j;
}
return ans;
}
}
}
答案 4 :(得分:0)
public static void main(String[] args) {
int maxNum, sum, counter; // input value
Scanner input = new Scanner(System.in);
System.out.print("How many odd numbers should I add up?: ");
maxNum = input.nextInt();
sum = 0;
for (counter = 1; counter <= maxNum; counter+=2)
{
sum += counter;
/*
Working of loop
counter = 1,sum = 1
counter = 3,sum = 4
counter = 5,sum = 9
counter = 7,sum = 16
counter = 9,sum = 25
*/
}
System.out.println("\n" + "The sum of the odd numbers between 1 and " + maxNum + " is: " + sum);
}
答案 5 :(得分:-1)
在你的for循环中,你将计数器增加一个
如果您只需要奇数,则应更改
for (counter = 1; counter < maxNum; counter++)
到
for (counter = 1; counter <= maxNum; counter+=2)
和
sum = counter + maxNum;
到
sum += counter;