如何在C语言中用do-while循环实现三角形边长条件校验?
解决三角形边长输入校验的do-while循环问题
核心思路是用一个合法性标志变量来控制循环:当输入不合法时,标记为需要重新输入,do-while循环就会继续执行;输入合法则退出循环,执行计算逻辑。以下是修改后的完整代码和关键说明:
关键调整点
- 新增
int invalid变量作为合法性标记,每次循环开始重置为0 - 调整错误判断顺序:先检查边长是否为非正数(负数或0本身就不合法),再判断三角形三边关系
- 每个错误分支中设置
invalid = 1,告知循环需要继续 - do-while的循环条件设为
invalid,即输入不合法时重复执行输入流程 - 错误提示添加换行符,优化输出可读性
修改后的完整代码
#include <stdio.h> #include <math.h> int main() { float a, b, c; float perimeter, half_p, height, square, median, bisector; int invalid; do { invalid = 0; // 每次循环重置合法性标记 printf("Enter the first side of the triangle: "); scanf("%f", &a); printf("Enter the second side of the triangle: "); scanf("%f", &b); printf("Enter the third side of the triangle: "); scanf("%f", &c); // 先校验边长是否为正 if (a <= 0) { printf("The number a must be positive\n"); invalid = 1; } else if (b <= 0) { printf("The number b must be positive\n"); invalid = 1; } else if (c <= 0) { printf("The number c must be positive\n"); invalid = 1; } // 再校验三角形三边关系(任意两边之和大于第三边) else if (a >= b + c) { printf("Invalid value: a is not smaller than the sum of b and c\n"); invalid = 1; } else if (b >= a + c) { printf("Invalid value: b is not smaller than the sum of a and c\n"); invalid = 1; } else if (c >= a + b) { printf("Invalid value: c is not smaller than the sum of a and b\n"); invalid = 1; } // 输入合法,执行计算逻辑 else { perimeter = a + b + c; half_p = perimeter / 2; printf("\nPerimeter of triangle: %.2f\n", perimeter); // 计算a边上的高 height = (2 * sqrt(half_p * (half_p - a) * (half_p - b) * (half_p - c))) / a; printf("Height on side a: %.2f\n", height); square = sqrt(half_p * (half_p - a) * (half_p - b) * (half_p - c)); printf("Area of triangle: %.2f\n", square); // 计算a边上的中线 median = 0.5 * sqrt(2 * pow(b, 2) + 2 * pow(c, 2) - pow(a, 2)); printf("Median on side a: %.2f\n", median); // 计算角A的角平分线(注意用2.0避免整数除法) bisector = (2.0 / (b + c)) * sqrt(b * c * half_p * (half_p - a)); printf("Angle bisector of angle A: %.2f\n", bisector); } } while (invalid); // 输入不合法时继续循环 return 0; }
额外提示
- 角平分线计算中
2要写成2.0,否则C语言会执行整数除法,导致结果错误 - 输出用
%.2f代替%f可以控制小数位数,让结果更整洁 - 代码中明确标注了高、中线、角平分线对应的边/角,避免歧义
内容的提问来源于stack exchange,提问作者hrytsenkoo
相关产品推荐
相关产品推荐

