problems with the multi condition in C -
i wrote code count operations +
, -
, *
, /
, factorial , others. problem code works 1 time . displays :
zadajte operaciu
it means "write want do". after first time when cycle over. displays :
zadajte operaciu:zadajte operaciu:
twice , don´t know why.
here code:
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int a,b,vysledok; char s; do{ printf("zadajte operaciu:"); s=getchar(); if(s=='+' || s== '-' ||s== '*' || s=='/' ||s== '^') { puts("operacia je binarna.\nzadaj prvy operand: "); scanf("%d",&a); puts("zadaj druhy operand: "); scanf("%d",&b); switch (s){ case '+': printf("vysledok je %d.\n",a+b); break; case '-': printf("vysledok je %d.\n",a-b); break; case '/': if(b==0) puts("chyba: nulou sa delit neda.\n"); else printf("vysledok je %d.\n",a/b); break; case '*': printf("vysledok je %d.\n",a*b); break; case '^': for(a;a>0;a--) b=b*b; printf("vysledok je %d.\n",b); break; }} else if(s== '!' || s=='s') { puts("operacia je unarna.\nzadaj prvy argument: "); scanf("%d",&a); switch (s){ case '!': vysledok=a; for(a;a>0;a--) vysledok=vysledok*a; printf("vysledok je %d.\n",vysledok); break; case 's': vysledok=sqrt(a); printf("vysledok je %f.\n",(float)vysledok); break; }} else if(s=='q') puts("zadany prikaz quit. ukoncujem."); } while (s!='q'); homecoming 0;
}
after entering values , press come in key (\n
). character stays in stdin
. in sec iteration,getchar
gets \n
character , not fulfill status in if
after it,the body of if
not executed , next iteration starts status in while
true,thus printing twice.
to remove character,you need clear stdin
c
No comments:
Post a Comment