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

C语言图形面积计算程序循环输入异常及功能改造咨询

图形面积计算程序改造

原程序说明

用于计算图形面积:

  • P:矩形(代码逻辑为正方形面积计算)
  • S:三角形
  • T:梯形

原程序代码:

#include <stdio.h>
#include <math.h>

int main()
{
    int base;
    int height;
    int side;
    int up;
    int down;
    int output;
    int i;
    char type[2];

    type[2] = getche();
    
    for(i = 0; i < 1000; i++)
    {
        if(type[i] == 'P')
        {
            scanf("%d", &side);
            getchar();
            
            output = side*side;
        
            printf("%d\n", output);
        }
        else if(type[i] == 'S')
        {
            scanf("%d %d", &base, &height);
            getchar();
            
            output = 0.5*base*height;
        
            printf("%d\n", output);
        }
        else if(type[i] == 'T')
        {
            scanf("%d %d %d", &up, &down, &height);
            getchar();
            
            output = height*(up+down)/2;
        
            printf("%d\n", output);
        }
    }

    return 0;
}

原程序问题

  1. 输入读取逻辑错误:仅在程序启动时读取一次类型,循环中访问type[i]会触发数组越界(数组仅2个元素,循环i上限为999),导致后续循环无法获取新输入
  2. 无有效终止机制:循环硬编码执行1000次,无法按需停止
  3. 精度丢失:三角形面积计算使用0.5*base*height浮点运算,但output为int类型,直接截断小数部分导致结果不准确
  4. 非标准函数依赖:getche()属于非标准C函数,移植性差

改造后代码

#include <stdio.h>

int main()
{
    char type;
    int side, base, height, up, down;
    int area;

    while (1)
    {
        // 过滤输入中的空白字符(换行、空格)
        type = getchar();
        while (type == '\n' || type == ' ')
        {
            type = getchar();
        }

        // 触发终止条件
        if (type == '0')
        {
            printf("0\n");
            break;
        }

        // 按图形类型计算面积
        switch (type)
        {
            case 'P':
                scanf("%d", &side);
                area = side * side;
                printf("%d\n", area);
                break;
            case 'S':
                scanf("%d %d", &base, &height);
                // 先乘后除避免小数截断
                area = base * height / 2;
                printf("%d\n", area);
                break;
            case 'T':
                scanf("%d %d %d", &up, &down, &height);
                area = height * (up + down) / 2;
                printf("%d\n", area);
                break;
            default:
                printf("无效输入\n");
                break;
        }
        // 清空输入缓冲区残留的换行符
        while (getchar() != '\n');
    }

    return 0;
}

改造要点

  • 循环逻辑重构:改为无限循环,每次循环开始时读取新的图形类型,实现多次输入功能
  • 终止条件实现:读取到'0'时输出0并退出循环,符合需求
  • 精度修复:三角形面积计算改为base * height / 2整数运算,避免小数截断问题
  • 输入处理优化:添加空白字符过滤逻辑,清除输入缓冲区残留内容,避免后续输入异常
  • 代码简化:移除不必要的数组和math.h依赖,用switch替代多重if-else,提升代码可读性

内容的提问来源于stack exchange,提问作者Aine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:55:17