使用scanf询问输入时,代码会产生无限循环

问题描述 投票:0回答:1

我有一个要求用户输入一个值来计算其平方根的函数,但是当我尝试验证输入的数字必须是数字而不是字符时,会造成无限循环

void opcion1(void){
    float A, K, i, aux;
    int awnser;
    ask:
    fflush( stdin );
        printf("enter the value for A: ");
        sleep(1);
        awnser = scanf("%f", &A);
    if(awnser < 1){ // not a number
        fputs("\nA is not a number\n", stderr);
        goto ask;
    }
    if(A < 0 ){
        aux = -A;
        i = sqrt(aux);
        if(A == (int)A) printf("\nthe square root of %.0f, is%.0fi", A, i);
        else printf("the square root of %.3f, is %.4fi", A, i);
    }else{
        K = sqrt(A);
        printf("the square root of A is %.2f", K);
    }
}

输出:

enter the value for A:
k
A is not a number
enter the value for A:
A is not a number
enter the value for A:
A is not a number
enter the value for A:
A is not a number
enter the value for A:
c validation scanf goto
1个回答
0
投票

主要问题是,当您刚开始使用该语言时,很难理解所有这些概念。就像scanf到底在哪里输入?什么是缓冲?

© www.soinside.com 2019 - 2024. All rights reserved.