You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C语言三角形面积计算代码输出始终为0?求原因及修正方案

Hey there! Let's break down why your code is always outputting 0, and fix it up step by step.

Why You're Getting 0 Every Time

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.

Fixed Code

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;
}
Quick Extra Tips
  • Your original printf lines (like printf("Get the height of the triangle",a);) had an extra a parameter that didn't do anything—since there's no %d placeholder in the string, C ignores it. The fixed code removes that.
  • Play with the printf format if you want: use %f for default precision, or %.1f to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:29:27