我自学C和我试图制作2个锻炼计划:
第一个拿一个数字并检查它是偶数还是奇数; 这是我为第一个提出的:
#include <stdio.h>
int main(){
int n;
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
return 0;
}
第二个应该将 n 数字作为输入,并计算输入的数字中的偶数,奇数和零的数量。输出应该是偶数,奇数和零的数量。
我想问一下如何在这种情况下实现循环:如果每个整数都可以接受,我怎么能设置一个EOF值(所以我不能,比方说,把0结束)?你能告诉我如何有效地构建这个短代码吗?
答案 0 :(得分:1)
#include <stdio.h>
int main(void) {
int n, nEven=0, nOdd=0, nZero=0;
for (;;) {
printf("\nEnter a number that you want to check: ");
//Pressing any non-numeric character will break;
if (scanf("%d", &n) != 1) break;
if (n == 0) {
nZero++;
}
else {
if (n % 2) {
nEven++;
}
else {
nOdd++;
}
}
}
printf("There were %d even, %d odd, and %d zero values.", nEven, nOdd, nZero);
return 0;
}
答案 1 :(得分:0)
检查scanf()
1,1填充字段(n)
填写0,0字段,可能为数字输入了类似“abc”的字符。
EOF,遇到文件结尾(或很少出现IO错误)。
#include <stdio.h>
int main(void) {
int n;
for (;;) {
printf("Enter a number that you want to check: ");
if (scanf("%d",&n) != 1) break;
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
}
return 0;
}
或读取随后阅读的数字计数:
int main(void) {
int n;
printf("Enter the count of numbers that you want to check: ");
if (scanf("%d",&n) != 1) Handle_Error();
while (n > 0) {
n--;
printf("Enter a number that you want to check: ");
int i;
if (scanf("%d",&i) != 1) break;
if((i%2)==0) {
if (i == 0) printf("%d is zero.\n",i);
else printf("%d is even and not 0.\n",i);
}
else
printf("%d is odd.\n",i);
}
return 0;
}
答案 2 :(得分:-1)
#include<stdio.h>
#include<conio.h>
void main()
{
int nodd,neven,num,digit ;
clrscr();
printf("Count number of odd and even digits in a given integer number ");
scanf("%d",&num);
nodd = neven =0; /* count of odd and even digits */
while (num> 0)
{
digit = num % 10; /* separate LS digit from number */
if (digit % 2 == 1)
nodd++;
else neven++;
num /= 10; /* remove LS digit from num */
}
printf("Odd digits : %d Even digits: %d\n", nodd, neven);
getch();
}
答案 3 :(得分:-2)
您可以这样做:
#include <stdio.h>
int main(){
int n,evenN=0,oddN=0,zeros=0;
char key;
do{
clrscr();
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if(n==0){
printf("%d is zero.",n);
zeros++;
}
else if((n%2)==0){
printf("%d is even.",n);
evenN++;
}
else{
printf("%d is odd.",n);
oddN++;
}
puts("Press ENTER to enter another number. ESC to exit");
do{
key = getch();
}while(key!=13 || key!=27) //13 is the ascii code fore enter key, and 27 is for escape key
}while(key!=27)
clrscr();
printf("Total even numbers: %d",evenN);
printf("Total odd numbers: %d",oddN);
printf("Total odd numbers: %d",zeros);
return 0;
}
此程序要求输入一个号码,评估号码,然后要求继续拨打另一个号码或退出。