我在我的圆计算器中包括cs50库,所以我可以从用户那里得到关于操作(周长/面积/体积)的输入,然后是半径,所以我想确保第一个输入是从1到3的数字,显示"请输入1到3的数字"在其他情况下,我不能处理else语句作为问题&;please choose operation:&;它被声明为浮点数,所以它只接受浮点数,否则它就会重新开始(只有除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");
}
}
如果你想让你的程序循环,直到用户输入一个介于1
和3
之间的数字,那么我建议你使用一个无限循环,一旦你确定输入是有效的,就显式地将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);}
}