【发布时间】:2016-03-17 02:56:22
【问题描述】:
我的 main 函数中有一个 while 循环,它调用一个用户定义的函数,该函数调用另一个用户定义的函数,该函数调用 scanf 来读取一对 double 值。我希望我的程序在输入非数字时结束。我的函数返回结构,而不是 0/1。有没有办法一直传递一个错误的scanf return 来打破我的 while 循环?
我可以声明一个全局变量并将其分配给scanf 语句,然后在main 函数中对该变量进行if 语句吗?
或者我是否必须更改我的函数以返回 int (0/1) 并通过引用传递我的结构?
这可能是一个非常糟糕的解释,所以这是我的问题中涉及的部分的代码......该程序旨在读取一个矩形(按左下角和右上角)和一个圆圈,并说出他们的区域重叠。而且我希望在main 函数中的while 循环中中断...
typedef struct{double x,y;} point;
typedef struct{point a,b,c,d;} rectangle;
typedef struct{point o; double r;} circle;
point readPoint(){
point p;
scanf("%lf%lf", &p.x, &p.y); //type "quit"
return p;
}
rectangle readRectangle(){
rectangle r;
r.c=readPoint();
r.b=readPoint();
r.a.x=r.c.x;
r.a.y=r.b.y;
r.d.x=r.b.x;
r.d.y=r.c.y;
return r;
}
int main(void) {
int a=0;
rectangle r;
circle c;
while(1){
printf("Enter rectangle:");
r=readRectangle(); //break loop here if quit is entered
printf("Enter circle:");
c=readCircle();
a=overlap(r, c);
if (a==1)
printf("The rectangle and the circle overlap.\n\n");
else
printf("The rectangle and the circle do not overlap.\n\n");
}
printf("Program completed normally.");
return EXIT_SUCCESS;
}
【问题讨论】:
-
您已经列出了一些主要选项。只需继续选择其中一个。我个人不建议使用全局变量,但会使用返回值方法。
-
除非必要,否则使用全局变量是不好的。
-
另一个选项在结构中再添加一项。
-
bansai,你能详细说明一下吗?您的意思是在点结构中添加另一个项目吗?像一个字符串来读取退出?这不会影响我使用该结构的其余时间吗?
-
我会创建
point *readPoint(point *p),然后检查scanf和if (scanf("%lf%lf", &p->x, &p->y) < 2) return NULL; return p;的返回值,并继续该逻辑备份链。
标签: c