请求调试三角形判断C代码:函数调用与运行报错问题
调试三角形判断C代码的崩溃问题
问题说明
我写了一段判断三边能否构成三角形的C代码,但程序执行到sum = sum_side(a)时就停止运行了。我怀疑是函数调用方式有问题,但试了各种方法都没解决,附上代码:
#include <cs50.h> #include <stdio.h> //is the size of the array const int n = 3; int sum_side(float x[]); int main(void) { float sum; int a[n]; sum = sum_side(a); // is used to get 3 sides from the user all have to be positive do { a[0] = get_int("First side: "); a[1] = get_int("Second side: "); a[2] = get_int("Third side: "); } while(a[0] <= 0 || a[1] <= 0 || a[2] <=0); //is used to say if it can be a triangle or nor if(sum_side(a[n]) == 1) { printf("Can be a triangle? "); } else { printf("Can't be a triangle? "); } } int sum_side(float x[]) { // Check that sum of any two sides greater than third if ((x[0] + x[1] <= x[2]) || (x[1] + x[2] <= x[0]) || (x[2] + x[0] <= x[1])) { return false; } // if we passe the test, we're good! return true; }
错误分析与调试建议
- 类型不匹配触发内存错误:
main里的数组a是int类型,但sum_side函数参数要求float数组。直接传递int数组会导致指针类型不兼容,函数访问时会按float格式解析int内存,触发未定义行为(崩溃)。 - 提前调用函数访问未初始化内存:
sum = sum_side(a)在用户输入三边前执行,此时数组a的元素是未初始化的垃圾值,函数访问这些值会直接导致程序崩溃。 - 函数调用参数错误:
sum_side(a[n])传递的是数组的第n个元素(即a[3],超出数组下标0-2的范围),而非数组本身。这会把一个int值当作float数组指针传递,完全不符合函数参数要求。 - 返回值与变量类型冗余:
sum是float类型,但sum_side返回int,且这个变量后续未被使用,完全可以删除。 - 未定义
true/false:标准C默认没有true和false宏,需包含<stdbool.h>头文件,或直接用1和0代替。
修正后的代码
#include <cs50.h> #include <stdio.h> #include <stdbool.h> // 引入头文件定义true/false const int n = 3; // 修改参数类型为int数组,匹配main中的数组类型 bool sum_side(int x[]); int main(void) { int a[n]; // 先获取用户输入,确保数组有有效值 do { a[0] = get_int("First side: "); a[1] = get_int("Second side: "); a[2] = get_int("Third side: "); } while(a[0] <= 0 || a[1] <= 0 || a[2] <=0); // 传递数组本身给函数,判断结果 if(sum_side(a)) { printf("Can be a triangle? Yes\n"); } else { printf("Can't be a triangle? Yes\n"); } } // 修改参数类型为int数组,返回值用bool更清晰 bool sum_side(int x[]) { // 三角形判断条件:任意两边之和大于第三边 if ((x[0] + x[1] <= x[2]) || (x[1] + x[2] <= x[0]) || (x[2] + x[0] <= x[1])) { return false; } return true; }
内容的提问来源于stack exchange,提问作者Shaind
相关产品推荐
相关产品推荐

