我试图获得5个整数输出并显示奇数,偶数,奇数总和甚至总数。这段代码给了我更大的总价值。问题是什么?
#include <stdio.h>
int main(){
int n,count,oc,ec;
float ot,et,answer;
for(count=0;count<=5;count++){
printf("enter a odd or even number :");
scanf("%d",&n);
}
answer=n%2;
if (answer>0){
oc=oc+1;
ot=n+ot;
}
else {
ec=ec+1;
et=n+et;
}
printf("odd counter is %f",oc);
printf("odd counter is %f",ot);
printf("even counter is %f",ec);
printf("even counter is %f",et);
}
答案 0 :(得分:1)
将累加器更改为整数并初始化它们:
int oc, ot, ec, et;
oc = ot = ec = et = 0;
按如下方式移动右括号:
for(count=0;count<=5;count++){
printf("enter a odd or even number :");
scanf("%d",&n);
answer=n%2;
if (answer>0){
oc=oc+1;
ot=n+ot;
}
else {
ec=ec+1;
et=n+et;
}
}
并将printf改为使用%d而不是%f
printf("odd counter is %d",oc);
printf("odd counter is %d",ot);
printf("even counter is %d",ec);
printf("even counter is %d",et);
答案 1 :(得分:0)
以下提议的代码:
#define
以及使用结果(有意义的)名称的位置。printf()
语句中的文字准确说明输出的值实际意味着什么for()
循环。gcc -c main.c -Wall -Wextra -pedantic -Wconversion -std=gnu11 -o main.o
gcc main.o -o main
./main
现在拟议的编码:
#include <stdio.h> // printf(), fprintf(), stderr, scanf()
#include <stdlib.h> // exit(), EXIT_FAILURE
#define MAX_INPUTS 5
int main( void )
{
int n;
int oc = 0;
int ec = 0;
int ot = 0;
int et = 0;
for( int count = 0; count < MAX_INPUTS; count++ )
{
printf("enter a odd or even number :");
if( 1 != scanf( "%d", &n ) )
{ // then input error
fprintf( stderr, "scanf for input %d failed\n", count+1 );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
if ( (n%2) > 0 )
{ // input was ODD
oc = oc + 1;
ot = n + ot;
}
else
{ // input was even
ec = ec + 1;
et = n + et;
}
}
printf( "number of odd inputs is %d\n", oc );
printf( "sum of odd inputs is %d\n", ot );
printf( "number of even inputs is %d\n", ec );
printf( "sum of even inputs is %d\n", et );
}
典型代码运行的输出:
enter a odd or even number :1
enter a odd or even number :2
enter a odd or even number :3
enter a odd or even number :4
enter a odd or even number :5
number of odd inputs is 3
sum of odd inputs is 9
number of even inputs is 2
sum of even inputs is 6