简体   繁体   English

如何防止输入类型为确定类型?

[英]how to prevent input type from being definite type?

i am including cs50 library in my circle calculator so i can get get input from user about operation(circumference/area/volume)then radius,so i want to make sure that first input is number from 1 to 3 by displaying "please enter a number from 1 to 3" in other conditions but i can't handle the else statement as the question "please choose operation:" is declared as float so it only accept floats or it will just start over(only numbers except 1,2,3 will cause the else statement not letters) code:我在我的圆形计算器中包含 cs50 库,所以我可以从用户那里获得关于操作(周长/面积/体积)然后半径的输入,所以我想通过显示“请输入一个”来确保第一个输入是从 1 到 3 的数字从 1 到 3 的数字”在其他条件下,但我无法处理 else 语句,因为问题“请选择操作:”被声明为浮点数,因此它只接受浮点数,否则它将重新开始(仅除 1,2 之外的数字, 3 会导致else语句不是字母)代码:

#include <stdio.h>
#include <cs50.h>
    
void get_circum(float radius);
void get_area(float radius);
void get_volume(float radius);

int main (void){
    printf("welcome in circle calculator,please select operation! \n");
    int operation = get_int("1-circumference \n2-area \n3-volume \n");
    if(operation==1 || operation==2 || operation==3){
        float radius = get_float("radius: \n");
        if(operation==1){get_circum(radius);}
        else if(operation==2){get_area(radius);}
        else if(operation==3){get_volume(radius);}
    }
    else if(operation !=1 && operation !=2 && operation !=3){
        printf("please enter a number from 1 to 3");
    }
}

If you want your program to loop until the user enters a number between 1 and 3 , then I recommend that you use an infinite loop and explicitly break out of the loop once you determine that the input is valid.如果您希望您的程序循环直到用户输入介于13之间的数字,那么我建议您使用无限循环并在确定输入有效后显式break循环。

#include <stdio.h>
#include <cs50.h>
    
void get_circum(float radius);
void get_area(float radius);
void get_volume(float radius);

int main( void )
{
    int operation;

    printf( "Welcome to circle calculator, please select operation! \n");

    //loop forever until input is valid    
    for (;;) //infinite loop, equivalent to while(1)
    {
        operation = get_int( "1-circumference \n2-area \n3-volume \n" );

        if ( operation == 1 || operation == 2 || operation == 3 )
        {
            //input is ok, so break out of infinite loop
            break;
        }

        printf( "Invalid input! Please enter a number from 1 to 3!\n" );
    }
    
    float radius = get_float("radius: \n");
    if      ( operation == 1 ) {get_circum(radius);}
    else if ( operation == 2 ) {get_area(radius);}
    else if ( operation == 3 ) {get_volume(radius);}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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