嗨,这就是我正在做的课程的问题......
程序应该打印用户键入的数字的平均值 (没有数字-1)。
5。程序应该打印出偶数和奇数的数量 用户输入(不带数字-1)。
我已经完成了1-4但是完全停留在5.我确实开始尝试解决这个问题,包括在我的while循环中放置一个for循环但是除了它没有工作的事实它看起来很不合适所以我删除了它。无论如何,这是我到目前为止所做的事情,正如我所说,所有这些都是以自己神奇的方式运作。
所以,如果有人能够帮我解决问题5 ,那就太棒了。我确定到目前为止我所做的事情本来可以写得更好,但是现在不要把注意力放在我身上,因为我和Java在一起这就是奇迹。
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int sum = 1; // to counteract the -1 from the user
int total = 0;
double avg;
//int even = 0;
//int odd = 0;
System.out.println("Type numbers:");
while (true) {
int numbers = Integer.parseInt(reader.nextLine());
sum += numbers;
total++;
avg = ((double) sum) / (total - 1);
if (numbers == -1) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + (total - 1));
System.out.println("Average: " + avg);
//System.out.println("Even numbers: " + even);
//System.out.println("Odd numbers: " + odd);
break;
}
}
}
}
答案 0 :(得分:0)
您可以存储变量,其中一个计数奇数,一个计数偶数。如果数字是奇数,则递增奇数变量。如果是偶数,则增加偶数变量。使用%运算符可以将输入的其余部分除以2。
int oddNumbers = 0;
int evenNumbers = 0;
if(numbers % 2 == 1){
oddNumbers++;
} else if(numbers % 2 == 0){
evenNumbers++;
}
答案 1 :(得分:0)
import java.util.Scanner; 公共课主要{
public static void main(String[] args) {
Scanner in= new Scanner (System.in);
int sum = 0;
System.out.print("Enter limit number: ");
int limit = in.nextInt();
int oddNumbers = 0;
int evenNumbers = 0;
for(int i= 1;i<=limit;i++)
{
System.out.println("Enter limit number: "+i+"");
int numbers= in.nextInt();
if(numbers %2==0)
{
evenNumbers++;
}
else if(numbers %2==1)
{
oddNumbers++;
}
}
System.out.println("There are: "+oddNumbers+" odd numbers");
System.out.println("There are :"+evenNumbers+" even numbers");
}
}
答案 2 :(得分:-2)
import java.lang.Math;
public class HelloWorld {
public static void main(String[] args) {
int firstnum = 4;
int lastnum = 104;
int evncnt, oddcnt;
int count;
System.out.println("First number is " + firstnum);
System.out.println("Last number is " + lastnum);
count = lastnum - firstnum + 1;
System.out.println("Total numbers are " + count);
if (count % 2 == 0) {
System.out.println("Total even numbers are " + count / 2);
System.out.println("Total odd numbers are " + count / 2);
} else {
if (firstnum % 2 == 0) {
System.out.println("Total Even numbers are ");
System.out.println((count + 1) / 2);
System.out.println("Total Odd numbers are ");
System.out.println((count - 1) / 2);
} else {
System.out.println("Total even numbers are ");
System.out.println((count - 1) / 2);
System.out.println("Total odd numbers are ");
System.out.println((count + 1) / 2);
}
}
}
}