CLion中C语言程序运行出现退出码-1073741819的问题求助
代码问题分析及修复
你的代码崩溃和功能异常主要来自以下几个问题:
scanf传参错误(导致崩溃的核心原因)
scanf函数要求传入变量的内存地址才能完成赋值操作,但你直接传递了变量的值:- 获取圆心坐标时,应该把
scanf("%d %d", circle.center.x, circle.center.y);修改为scanf("%d %d", &circle.center.x, &circle.center.y);(用&取地址) - 获取半径时,同样需要传地址,并且格式符要匹配变量类型,原代码的
scanf("%d", circle.radius);完全错误,后面会详细说明。
- 获取圆心坐标时,应该把
格式符与变量类型不匹配
你的circle.radius是double类型,但你用了整数格式符%d,这会导致内存读写混乱,必须换成适配double的%lf,同时加上地址符,正确写法是:scanf("%lf", &circle.radius);拼写错误
输出面积的语句中The arae of the circle是拼写错误,应该改为The area of the circle;提示文本里的fomat也写错了,应为format。变量命名冗余/混淆
Round函数里定义了和函数名同名的局部变量double Round = 0;,虽然语法合法,但容易造成阅读混淆,其实这个变量完全可以省略,直接返回计算结果更简洁。
修复后的完整代码
#include <stdio.h> #include <math.h> #define pi 3.1415926535 struct point { int x; int y; }; struct circle { struct point center; double radius; }; double Area(struct circle circle) { // s = πr² return circle.radius * circle.radius * pi; } double Round(struct circle circle) { return 2 * pi * circle.radius; } int main(void) { struct circle circle = {0, 0, 0}; printf("The center of the circle (format : x y) : "); scanf("%d %d", &circle.center.x, &circle.center.y); printf("The radius of the circle : "); scanf("%lf", &circle.radius); printf("The area of the circle : %f\n", Area(circle)); printf("The perimeter of the circle : %f\n", Round(circle)); return 0; }
内容的提问来源于stack exchange,提问作者신현섭
相关产品推荐
相关产品推荐

