为何C语言三角形面积计算代码输出始终为0?求原因及修正方案
Hey there! Let's break down why your code is always outputting 0, and fix it up step by step.
There are two key issues causing this problem:
1. Integer Truncation from Mismatched Variable Types
You declared c as an int (integer), but the area of a triangle is almost always a floating-point number (like 0.5 when base and height are both 1). In C, when you assign a float/double value to an integer variable, it chops off the decimal part entirely—no rounding, just straight truncation.
So if your calculation gives you 0.5, c becomes 0. Even if you input larger numbers that should give a whole number (like base=4, height=3, area=6), it might work sometimes, but any non-whole number result will get cut down to the nearest lower integer. If you're testing with small values, that's why you only see 0 every time.
On top of that, your t=0.5 is a double (floating-point), and a*b is an integer. Multiplying them gives a double, but shoving that into an int variable guarantees you'll lose decimal data.
2. A Pointless Extra Input
That final scanf("%d",&c); does nothing useful—it just makes the program wait for another input after outputting the area, which is confusing and unnecessary.
We'll switch to a floating-point type for the area, fix the print statements, and clean up the extra bits:
#include <stdio.h> int main(void) { int a, b; double c; // Use double to store the floating-point area printf("Enter the height of the triangle: "); scanf("%d", &a); printf("Enter the base of the triangle: "); scanf("%d", &b); c = 0.5 * a * b; // No need for a separate t variable—compute directly printf("The area of the triangle: %.2f\n", c); // %.2f shows 2 decimal places for clarity return 0; }
- Your original
printflines (likeprintf("Get the height of the triangle",a);) had an extraaparameter that didn't do anything—since there's no%dplaceholder in the string, C ignores it. The fixed code removes that. - Play with the
printfformat if you want: use%ffor default precision, or%.1fto show just one decimal place. - For robustness, you could add checks to make sure the user enters positive numbers (since a triangle can't have a negative base or height!).
内容的提问来源于stack exchange,提问作者Xander ovrload

