简体   繁体   中英

Error regarding a simple C program involving scanf()

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
int main() {
    double NET_Income = 9999.58;
    printf("Enter your NET monthly income: ");
    scanf("%f", &NET_Income);

    while (NET_Income < 500.00) OR (NET_Income > 400000.00); {
        printf("Sorry, that is an incorrect amount, please re-enter your NET monthly income: ");
        scanf("%f", &NET_Income);
    }
    return 0;
}

When I try to run this code in visual studio I get the following errors:

Return value ignored: 'scanf'

Warning C4477 'scanf': format string '%f' requires an argument of type 'float *', but variadic argument 1 has type 'double *'

Warning C4013 'OR' undefined; assuming extern returning int

'scanf' : format string '%f' requires an argument of type 'float *', but variadic argument 1 has type 'double *

There are quite a few problems with this code:

  • as noted in the comments, the scanf format specifier for a double is %lf , not %f

  • the return value from scanf indicates whether the function succeeded or not, and should be checked ( documentation )

  • while .NET_Income < 500.00) OR .NET_Income > 400000.00); { while .NET_Income < 500.00) OR .NET_Income > 400000.00); { contains several errors, including use of OR (which doesn't exist) and some unwanted extra brackets. Also, you don't want that semi-colon in there, although perhaps that's just a typo. Anyway, it should be: while .NET_Income < 500.00 ||.NET_Income > 400000.00) {


There have been some points raised in the comments about the return value of scanf , so I thought I would clarify. cppreference defines it as:

Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.

Where 'input failure', means that input characters were unavailable, and 'matching failure', means that the input was inappropriate (eg, in this case, not numeric).

So, in this case, since we are only scanning for a single argument at a time, a return value of 1 means success', and anything else means failure. You might attempt some kind of recovery strategy if scanf fails, but that is beyond the scope of this question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM