如何进行拒绝字符、空格和额外小数点的错误控制?
该程序要求用户键入一个初始值,该值允许范围在 0 到 1000 之间,包括小数点位置。
如何创建错误控制来拒绝字符、空格或附加小数点位置,例如 1.2.3? n 循环自身以提示用户输入新内容
printf("Please enter initial velocity(in m/s) of ball when thrown vertically upwards: \n");
scanf("%lf%c",&v0,&rubbish);
printf("%f\n",v0);
printf("%c\n",rubbish);
/*error control for incorrect range of value entered*/
while (v0<0 || v0> 1000|| rubbish !='\n')
{
/*Ask user for correct value of velocity*/
v0='\n', rubbish="\n";
printf("\nIncorrect value keyed\n");
printf("Please enter again the initial velocity(in m/s) of ball when thrown vertically upwards: \n");
scanf("%lf",&v0);
scanf("%c",&rubbish);
printf("%f\n",v0);
printf("%c\n",rubbish);
}
the program requires user to key in an initial value which allows for range between 0 to 1000 including decimal placing
how to create error control to reject characters, spacing, or additional decimal point placed such as 1.2.3? n loop itself to prompt user for new input
printf("Please enter initial velocity(in m/s) of ball when thrown vertically upwards: \n");
scanf("%lf%c",&v0,&rubbish);
printf("%f\n",v0);
printf("%c\n",rubbish);
/*error control for incorrect range of value entered*/
while (v0<0 || v0> 1000|| rubbish !='\n')
{
/*Ask user for correct value of velocity*/
v0='\n', rubbish="\n";
printf("\nIncorrect value keyed\n");
printf("Please enter again the initial velocity(in m/s) of ball when thrown vertically upwards: \n");
scanf("%lf",&v0);
scanf("%c",&rubbish);
printf("%f\n",v0);
printf("%c\n",rubbish);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将其理解为:您想从用户那里获得双倍(我将您的评论中的“键入”理解为“在键盘上键入”)。附加约束是输入行不应包含任何其他字符或额外的小数。
您可以分两步完成:
read line from stdin
此时 s 包含用户输入。
使用
strtod()
解析双精度strtod()
可以检测许多错误情况:溢出、下溢、空字符串或前导非空白字符无法解释为浮点数。接口可能会令人困惑(并且 c89 和 c99 之间的一些极端情况发生了变化)。您可以查看并选择您想要检测并忽略其他条件的条件。下面是一个示例,要求字符串仅包含数字和可选的前导、尾随空格,仅包含其他内容:
I understand it as: you'd like to get a double from a user (I understand "keyed" in your comment as "typed on keyboard"). With additional constraint that input line should not contain any other characters or extra decimals.
You could do it in two steps:
read line from stdin
At this point
s
contains user input.parse double using
strtod()
strtod()
can detect many error conditions: overflow, underflow, empty strings, or leading non-whitespace characters can't be interpreted as a floating-point number. The interface might be confusing (and some corner cases changed between c89 and c99). You can peek and choose what conditions you'd like to detect and ignore others.Here's an example that requires that the string contained only a number and optional leading, trailing whitespace and nothing else: