I have only been learning C language for about a month.
The code below is a program that adds the value when a single natural number is entered and does not accept other characters. When E is pressed, the for statement is finished and the total and average are output.You can't make any significant changes because it's in line with the challenges.
I have a question.
This code will print "Illegal Input" even if you enter a single natural number.
I don't understand why else if
and else
run at the same time.Please teach me.
#include<stdio.h>
int main() {
charc;
int sum = 0, count;
for(count=0; count>=0;){
scanf("%c", & c);
if(c=='E'){
printf("Sumis:%d\n",sum);
printf("Average is: %f\n", (float) sum/count);
break;
} else if(c>'0'&c<='9'){
sum+=(int)c-48;
count+=1;
} else {
printf("Illegal input:%c\n",c);
}
}
return 0;
}
The reason seems to be a new line code. I think you can modify the else
clause as follows.
} else{
if(c=='\n') {continue;}
printf("Illigal input: %c\n", c);
}
This is my personal opinion, but in this case, I thought the while
loop would be better than the for
loop.I don't know where the big changes will start, so please refer to the following for your reference.
#include<stdio.h>
# include <string.h>
int main(const int argc, const char*argv[]){
char str[2]="";
int sum = 0;
int count = 0;
while(NULL!=fgets(str,sizeof(str),stdin)){
const charc=str[0];
if(c=='E'){
printf("Sumis:%d\n",sum);
printf("Average is: %f\n", (float) sum/count);
break;
} else if('0'<c&'10'>c){
sum+=(int)c-48;
count+=1;
} else{
if(c=='\n') {continue;}
printf("Illigal input: %c\n", c);
}
}
return 0;
}
© 2024 OneMinuteCode. All rights reserved.