有人能开发这个程序吗?用c语言开发一个程序,反复从键盘上收集一个正数,如果用户输入一个负数,它应该忽略它,并继续收集这个数字,直到用户输入零。程序然后显示集合中的所有偶数和奇数的列表以及所有数字的和。
这是我试过的程序..。
#include <stdio.h>
int main()
{
int num, even, odd, total_of_num;
printf("Enter a Positive Number: ");
scanf("%d", &num);
for (num; num<=50; num++)
{
if (num >= 0)
{
if (num%2==0)
{
even=num;
printf("%d ", even);
}
else
{
odd=num;
printf("%d", odd);
}
}
else
{
printf("Sorry! Negative number is not acceptable, Enter a positive Number\n");
}
}
return 0;
}
发布于 2022-12-04 18:25:25
这里有一个用C语言实现的程序,它反复从键盘收集正数,忽略负数,并显示收集到的所有偶数和奇数以及所有数字的和:
#include <stdio.h>
int main()
{
int num;
int even_sum = 0;
int odd_sum = 0;
int total_sum = 0;
// Collect positive numbers from the keyboard
printf("Enter positive numbers (enter 0 to end):\n");
do
{
scanf("%d", &num);
// Ignore negative numbers
if (num < 0)
{
continue;
}
// Keep track of the sum of all numbers
total_sum ++;
// Keep track of the sum of even and odd numbers separately
if (num % 2 == 0)
{
even_sum ++;
}
else
{
odd_sum ++;
}
}
while (num != 0);
// Display the sums of even and odd numbers
printf("Sum of even numbers: %d\n", even_sum);
printf("Sum of odd numbers: %d\n", odd_sum);
printf("Total sum: %d\n", total_sum);
return 0;
}
这个程序使用一个do-while循环来重复收集键盘上的数字,直到用户输入0。在循环内部,如果用户输入负数,则使用continue关键字跳过循环的当前迭代。它还跟踪偶数和奇数的和,以及所有数字的总和。最后,它在程序结束时显示所有这些总和。
我希望这能帮到你!如果你还有其他问题,请告诉我。
发布于 2022-12-04 18:27:12
#include <stdio.h>
int main()
{
// Define variables for storing the input numbers,
// their sum, and the counts of even and odd numbers.
int num, sum = 0, even_count = 0, odd_count = 0;
// Read numbers from the keyboard repeatedly until the user inputs 0.
while (1)
{
printf("Enter a number: ");
scanf("%d", &num);
// If the user inputs a negative number, ignore it and continue.
if (num < 0)
{
continue;
}
// If the user inputs 0, stop reading numbers.
if (num == 0)
{
break;
}
// If the number is positive, add it to the sum.
sum += num;
// Check if the number is even or odd and increment the corresponding count.
if (num % 2 == 0)
{
even_count++;
}
else
{
odd_count++;
}
}
// Print the results.
printf("Total number of even numbers: %d\n", even_count);
printf("Total number of odd numbers: %d\n", odd_count);
printf("Sum of all numbers: %d\n", sum);
return 0;
}
https://stackoverflow.com/questions/74679637
复制相似问题