如何检查输入是否为负数?

How to check if the input is negative?

程序从用户那里收到一个账号,不能为负。

有没有其他方法可以检查是否为负值?

#include <stdio.h>
    
int main(int argc, char * argv[])
{
    int account = 0;
        
    printf("Enter your account number:\n");
    scanf("%d", &account);
        
    while(account<0)
    {
        printf("Error: Enter a valid account number.\n");
        scanf("%d", &account);
    }
}

您只能从用户输入中安全地读取 char,因此您需要读取 char * 然后将它们转换为其他类型。对于您的问题,您可以这样做:

char account_str[MAX_CHAR];
unsigned int account = 0;
bool check = false;

printf("Enter your account number:\n");
do
{
    fgets(account_str, MAX_CHAR, stdin); // read the account number (as string)
    check = isPosNumStr(account_str);
    // isPosNumStr is a personal function that determine if a string have only
    // digit and is positive
    if (!check) {
        printf("Error: Enter a valid account number.\n"); 
    }
} while (!check)
account = atoi(account_str); // convert string to int
#include <stdio.h>
/* For the account number you should use a "long" instead a "int", 
And this happens because the account number needs a bigger allocation of memory.
I recomend you to look for "int" limits to understand this.*/

long NumbAccount;

void main(){
    printf("Enter your account number:\n");
scanf("%ld", &NumbAccount);

while(NumbAccount<0)
{
    printf("Error: Enter a valid account number.\n");
    scanf("%ld", &NumbAccount);
}
}

虽然问题没有提供导致您注意到的行为的示例输入,但您可能遇到了 溢出 问题。

int 类型,在大多数现代机器中使用 4 个字节存储,可以表示从 -2,147,483,648 到 2,147,483,647 的整数。如果您提供的值大于最大正数 (INT_MAX),则该值将需要存储更多的字节数,因此在实际存储的字节中,最高有效位的信息将丢失,结果值可能最终处于负值范围内。对于大的负值也会发生同样的情况。

你可以做的是使用 长整数 以便使用 8 位并且范围更大:从 -9223372036854775808 到 9223372036854775807。

long num;
scanf ("%ld", &num);

我想强调的是,无论您使用多少字节,计算机中的数字表示总是有限的。如果这些限制不符合您的应用要求,您将不得不改变您的方法,

  • 使用 strtol,如果发生溢出或下溢,它会用适当的 return 值警告您
  • 获取整个字符串并自行解析