C, with a variable error (for the source code of the calculator program)

Greetings, today, when I try something new (a concept and style that suddenly appear in my mind), I came across several problems that I don’t understand why this happened.

The code

// This program would get two numbers from user , and request for an arithmetic operator , and carry out arithmetic.

 #include <stdio.h>


int main(void)
{
    int fNum;
    int sNum;
    int status = 1;
    int operator;
    int ans;

    printf("Enter the first operand :");
    while(scanf("%d" , &fNum) == 0)
        ;
    printf("Please enter the second operand :");

    while(scanf("%d" , &sNum) == 0)
        ;    
    printf("Which operator you wanted to use\n");
    printf("1 for +\n2 for -\n");


   while(status)
   {

     scanf("%d" , &operator);
     status = 0;

     switch(operator)
     {
           case 1:
             ans = fNum + sNum;
              break;

           case 2:
             ans = fNum - sNum;
             break;

           default:
             status = 1;
     }
   }

    printf("The answer is %d\n" , ans);

    return 0;
}

My analysis and question

First part:

1.) There is one thing that I don’t understand when I try to run this code, I get a warning from the compiler, "C: \ Users \ Znet \ Documents \ Pelles C Projects \ Test1 \ Test.c (10): warning # 2229: local "ans" are potentially used without initialization. , But of course I can still run the program since this is not an error message.

2.) , , , ans, (0 ), ? , ans switch, ? ( ) , , .

:

1.) switch, 1, 2 .

2.) 1 2, , , , .

3.) , , , , , , , . , , .

4.) , ​​, , ?



, :)

+3
3

:

, ans ( switch). , - . , - .

:

- . scanf. , scanf . " , , ". while . , , , .

+2
    • Q: " № 2229: " ans " ."

    • A: , ans ( ) - , , - . int ans = 0; .

    • Q: , , , , , . , , .

.

do { 
    printf("Which operator you wanted to use\n");
    printf("1 for +\n2 for -\n");
} while ( scanf("%d", &operator) != 1 );

scanf --- , 0. ; .

0

, . , . , .

int main()
{
   /* NOTE: 'f' is uninitialized */
   int f, n;

   printf ("\nn : ");
   scanf ("%d", &n);

   while (n)
    f = f * n--;

   printf ("\nfactorial = %d", f);
   return 0;
}

undefined. f - (automatic), , main f , , f. . , int f = 1;, . , , , . , ans = 0; .

-. , 12 - , , . , "%d" scanf ("%c%c",&var1, var2);, . , "%d", , ( ), . operator . scanf . , , , 0, . , operator 1. :

/* Ask for input while the user does not input a 
 * valid integer.
 */
while (scanf ("%d", &operator) != 1)
{
   /* Body is entered whenever an invalid integer is entered */
   /* Your message */
}
/* When the user inputs a valid integer the condition 
 * in 'while' loop is false and program continues 
 */
0

All Articles