java求答案
有时间给你写了,如下代码,有注释的:
import java.util.Scanner;
/**
* 用户输入n1和n2:求不能同时被3和5整除的累加和
* @author 你好qiulinhe
*
*/
public class Ceshi {
public static void main(String[] args) {
System.out.println("请输入第一个数据n1");
Scanner scan1= new Scanner(System.in);
int n1= scan1.nextInt();
System.out.println("请输入第二个数据n2");
int n2= scan1.nextInt();
if(n1>n2){
System.out.println("n1应该小于n2,请重新输入");
n1= scan1.nextInt();
n2= scan1.nextInt();
}
System.out.println("您刚才输入的两个数据为"+n1+"--"+n2);
//循环遍历判断n1和n2不能同时被3和5整除的累加和
int sum=0;//n1和n2不能同时被3和5整除的累加和
for(int i=n1;i<n2;i++){
if(!(i%3==0 && i%5==0))//判断不能同时被3和5整除的,其实是判断取余是否为0
{
sum+= i;
System.out.println("不能同时被3和5整除的数为:"+i);
}
}
System.out.println("n1和n2不能同时被3和5整除的累加和为:"+sum);
}
}
运行结果为:
public class Demo{
public static void main(String[] arg0){
int sum = 0;
Scanner in =new Scanner(System.in);
System.out.println("请输入开始的整数");
int start = in.nextInt();
System.out.println("请输入终止的整数");
int end = in.nextInt();
for(int i = start;i<end;i++){
if(!isTh(i))
sum = sum+i;
}
System.out.println("符合要求的数的和为:" +sum);
}
public static boolean isTh(int num){
return num%3==0&&num%5==0;
}
}
2017-01-05
Scanner sc = new Scanner(System.in);
System.out.println("请输入整数n1:");
int n1 = sc.nextInt();
System.out.println("请输入整数n2:");
int n2 = sc.nextInt();
int total = 0;
for(int i=n1; i<=n2; i++){
if(i%3 == 0 && i%5 == 0){
continue;
}
total += i;
}
System.out.println("和为: " + total);