(Visual Studio)Calculation _using for sentence

Viewed 27

Want to elicit average of entered real value,until negative value is entered. My problem is

  1. My calculation don't quit when negative value is entered

  2. It keep asks printf sentence for 3 time. What did I do wrong?

    #include <stdio.h>
    
    int main(void)
    {
     double total = 0.0;
     double input=0.0;
     int num = 0;
    
     for (; input >= 0.0;)
     {
         total += input;
         printf("real number(minus to quit):");
         scanf_s("%1f", &input);
         num++;
     }
     printf("average:%f \n", total / (num - 1));
     return 0;
    }
    
1 Answers

you have many problems with your code :

  1. it's not %1f in the line scanf_s("%1f", &total); as %1f will give you undefined behavior , it's %lfas you are scanning a double , there is a big difference between number one and lower case L

  2. the function called scanf returns an integer indicating how many elements could be assigned to the input that the user entered , so , you should do if(scanf_s("%lf", &input) == 1) to check if the assignment done successfully, that will help you in detecting if - is entered instead of the number

  3. if the user entered a lonely - then sacnf will fail to convert and you have to take another approach

  4. when you are printing the average in this line : printf("average:%f \n", total / (num - 1)); , you actually prints a double , so it's %lf instead of %f

  5. the condition of the for loop is incorrect , you are saying for (; input >= 0.0;) but this will prevent you from entering any negative values as when entering a negative value , the for loop will break , so you could use while(1) instead of the for loop and only break when a - is entered alone


so here is my edited version of yours , I introduced a dummy string to read the buffer and check whether the input was a lonely - or not , and if not then I try to convert it to double and here is my edited solution :

      #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        char dummy[30];
        double total = 0.0;
        int num = 0;
        double DecimalConverted = 0;
    
        while(1)
        {
    
            printf("real number(minus to quit):");
            fgets(dummy, 30, stdin);    // gets the input into the buffer
    
            if(dummy[0] == '-' && dummy[1] == '\n') // break from the loop on condition that '-' only entered
                break;
    
            // convert the string to decimal
            DecimalConverted = strtod(dummy ,NULL);
            if(DecimalConverted == 0)
                printf("not a number\n");
            else{
                total += DecimalConverted;
                num++;
            }
    
        }
        printf("average:%lf \n", total / (num - 1));
        return 0;
    }

and here is the output :

real number(minus to quit):12
real number(minus to quit):-51
real number(minus to quit):-
average:-39.000000
Related