在C中尝试语句?

时间:2011-10-08 10:00:15

标签: c

C中是否有try语句?我想制作一个梯形的“面积计算器”。我希望用户只输入数字:

#include <stdio.h>
#include <conio.h>

main()
{
 clrscr();
 float base1, base2, height, area;
 printf("This program will compute the area of your trapezoid. Enjoy!");
 printf("\n\tPlease enter the length of base1: ");
 scanf("%f", &base1);
 printf("\tPlease enter the length of base2: ");
 scanf("%f", &base2);
 printf("\tPlease enter the length of height: ");
 scanf("%f", &height);
 area = (base1 + base2) * h / 2;
 printf("\nThe area of your trapezoid is: ", area);
 getch();
}

但是,他们可以自由输入非数字数据。这样做会使程序崩溃。我该怎么做才能检查它是否是正确的数据?我相信这可以通过循环完成,但由于一个程序有很多解决方案,我怀疑我的效率最高。

3 个答案:

答案 0 :(得分:5)

C没有异常,因此没有try语句,它是 C ++ 功能,而不是C语言。你可以set up something similar yourself using longjmp()/setjmp(),虽然我个人不会试图重新发明那个轮子。

答案 1 :(得分:1)

不,不是

一般 try语句只存在于面向对象的语言中,如Python,C ++,Objective-C,C#,Visual Basic,Java等。

答案 2 :(得分:1)

错误处理在C语言中明确表示,if()goto。异常处理(例如除以0)取决于底层内核(Unix上的信号处理,大多数RTOS上的CPU陷阱处理)。

Ada拥有exception机制,能够raise用户定义的例外。