📅  最后修改于: 2023-12-03 15:11:03.072000             🧑  作者: Mango
介绍:
这个Java程序可以通过输入一个正整数N,计算出第一个N个奇数和偶数之和。
步骤:
import java.util.Scanner; //导入Scanner类
public class CalculateSum{
public static void main(String[] args){
Scanner input = new Scanner(System.in); //创建Scanner对象
int N = input.nextInt(); //读取用户输入的整数N
}
}
public class CalculateSum{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int oddSum = 0; //定义奇数和
int evenSum = 0; //定义偶数和
for(int i = 1; i <= N; i++){
if(i % 2 == 0){ //判断是否为偶数
evenSum += i; //累加偶数和
}
else{ //否则为奇数
oddSum += i; //累加奇数和
}
}
}
}
public class CalculateSum{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int oddSum = 0;
int evenSum = 0;
for(int i = 1; i <= N; i++){
if(i % 2 == 0){
evenSum += i;
}
else{
oddSum += i;
}
}
System.out.println("前" + N + "个奇数和为:" + oddSum);
System.out.println("前" + N + "个偶数和为:" + evenSum);
}
}
完整代码:
import java.util.Scanner;
public class CalculateSum{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int oddSum = 0;
int evenSum = 0;
for(int i = 1; i <= N; i++){
if(i % 2 == 0){
evenSum += i;
}
else{
oddSum += i;
}
}
System.out.println("前" + N + "个奇数和为:" + oddSum);
System.out.println("前" + N + "个偶数和为:" + evenSum);
}
}
返回markdown格式: