c语言31
.编写程序,输入一批正整数(以零或负数为结束标志),求其中的偶数和。要求定义和调用函数even(n)判断数的奇偶性,当n为偶数时返回1,否则返回0。#include <stdio.h>
int even(int n)
{
if(n%2==0)
return 1;
else
return 0;
}
int main()
{
int n,sum=0;
printf("Input integers: ");
do{
scanf("%d",&n);
if(even(n)==1)
continue;
else
sum=sum+n;
}
while(n>0);
printf("The sum of the odd numbers is %d",sum);
return 0;
} #include <stdio.h>
int even(int);
int main(void)
{
int n, sum=0;
printf("Input integers:\n");
do
{
scanf("%d",&n);
if(even(n)==1)
sum += n;
// 去掉scnaf最后 一个字符 \n
while(getchar() != '\n')
continue;
}while(n !=0 );
printf("The sum of the odd numbers is %d \n",sum);
return 0;
}
int even(int n)
{
if(n%2==0)
return 1;
else
return 0;
}
#include <stdio.h>
int even(int n)
{
if(n%2==0)
return 1;
else
return 0;
}
int main()
{
int n,sum=0;
printf("Input integers: ");
do{
scanf("%d",&n);
if(n<=0)
break;
else if(even(n)==1)
sum=sum+n;
}
while(1);
printf("The sum of the odd numbers is %d",sum);
return 0;
} 本帖最后由 mgsky1 于 2018-1-17 13:15 编辑
问题出在当输入0或者-1的时候,本来要退出了,但是还是会继续操作
还有就是你算的是奇数和,不是偶数,要把if条件改一下,函数返回值为1的时候相加
#include <stdio.h>
int even(int n)
{
if(n%2==0)
return 1;
else
return 0;
}
int main()
{
int n,sum=0;
printf("Input integers: ");
while(scanf("%d",&n) != EOF)
{
if(n <= 0) break;
if(even(n)==0)
continue;
else
sum=sum+n;
}
printf("The sum of the odd numbers is %d",sum);
return 0;
}
页:
[1]