我的伪代码:
最佳情况: 1)询问用户号码 2)测试用户的输入是否为数值 3)如果用户输入有效,则对用户输入执行落地,倒圆和天花板功能 4)显示用户输入的下限,下限和上限值
最坏的情况: 1)询问用户号码 2)测试用户的输入是否为数值 3)如果用户输入无效,请询问用户是否要使用“是/否”选择重试 4)如果用户说是,请返回1),如果用户说否-终止
#include <stdio.h>
#include <math.h>
int main(void) {
float user_input;
int a;
char answ;
do {
printf ("Enter a number to find its lower bound, rounded, and upper bound values: ");
if ((a = scanf("%f", &user_input) == 1)) {
float floored_input = floor(user_input);
float rounded_input = round(user_input);
float ceiled_input = ceil(user_input);
printf("Lower Bound: %1.0f\n", floored_input);
printf("Rounded: %1.0f\n", rounded_input);
printf("Upper Bound: %1.0f\n", ceiled_input);
break;
} else {
printf("Invalid input. Do you want to try again? (Y/N): ");
scanf("%c", &answ);
}
} while(answ == 'Y' || answ == 'y');
return 0;
}
我唯一的问题是,当用户输入的字面值不是'i'时,程序终止,并且我返回工作目录。
用户可以输入任何数字,它将起作用。 用户可以输入i,然后系统会提示他或她
但是,当用户输入“ i2”,“ hello”,“ h”,“ b”,“ yoooo”等时
用户没有选择“是/否”,程序被终止
答案 0 :(得分:0)
以下建议的代码:
ctype.h
函数:toupper()
float
值使用适当的功能answ
现在,建议的代码:
#include <stdio.h>
#include <math.h>
#include <ctype.h>
int main(void)
{
float user_input;
char answ = 'Y';
while( toupper( answ ) != 'N' )
{
printf ("Enter a number to find its lower bound, rounded, and upper bound values: ");
if ( scanf("%f", &user_input) == 1 )
{
float floored_input = floorf( user_input );
float rounded_input = roundf( user_input );
float ceiled_input = ceilf( user_input );
printf( "Lower Bound: %1.0f\n", floored_input );
printf( "Rounded: %1.0f\n", rounded_input );
printf( "Upper Bound: %1.0f\n", ceiled_input );
}
do
{
printf( "Do you want to try again? {Y/N}: " );
scanf( " %c", &answ );
//printf( "debug: answ = %x\n", answ );
} while( toupper(answ) != 'Y' && toupper( answ ) != 'N' );
}
return 0;
}