我目前仍然坚持使用MOOC练习36.我的问题是我不能让我的程序存储奇数和偶数。我理解我需要使用模数运算符%2,这样程序就可以找到提示是0 - 1是一个偶数还是奇数。
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int tal; //Min reader funktion
int sum = 0;
int numbersTyped = 0;
double average = 0.0;
int even = 0;
int odd = 0;
while (true) {
tal = Integer.parseInt(reader.nextLine());
if (tal == -1){
System.out.println("Thank you and see you later!");
System.out.println("The sum is: " + sum);
System.out.println("How many numbers: " + numbersTyped);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
if (tal >= 0){
sum += tal;
numbersTyped++;
average = (double) sum / (double) numbersTyped;
} else if (tal > 0){
tal %= 2;
even = tal;
} else if (tal > 1) {
tal %= 2;
odd = tal;
}
}
}
答案 0 :(得分:1)
尝试执行此代码:
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int tal; //Min reader funktion
int sum = 0;
double doubleSum =0.0d;;
int numbersTyped = 0;
double doubleNumbersTyped = 0.0d;
double average = 0.0;
int even =0;
int odd = 0;
while (true) {
tal = Integer.parseInt(reader.nextLine());
if (tal == -1){
System.out.println("Thank you and see you later!");
System.out.println("The sum is: " + sum);
System.out.println("How many numbers: " + numbersTyped);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
if (tal >= 0){
sum += tal;
numbersTyped++;
doubleSum = (double) sum;
doubleNumbersTyped = (double) numbersTyped;
average = doubleSum / doubleNumbersTyped;
}
if (tal > 0 && tal %2==0){
even++;
}
if (tal > 1 && tal %2!=0) {
odd++;
}
}
答案 1 :(得分:0)
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers:");
int sum=0;
int i=0;
int even=0;
int odd=0;
double average=0.0;
while (true) {
int number=Integer.parseInt(reader.nextLine());
if (number!=-1) {
sum+=number;
i++;
average=(double)sum/(double)i;
}
if (number==-1) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is "+sum);
System.out.println("How many numbers:"+i);
System.out.println("The average is "+average);
System.out.println("Even numbers "+even);
System.out.println("Odd numbers "+odd);
break;
}
if (number%2==0) {
even++;
}
if (number%2!=0) {
odd++;
}