ACM - 之前的一些总结

本文介绍了C语言编程中的一些实用技巧,包括如何通过预处理指令控制文件读取、使用const定义常量的优势,以及处理浮点数时可能遇到的陷阱及解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于之前的一些题目的总结。

利用def来控制编译是否使用freopen

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

int main()
{
#ifdef DEBUG
    freopen("input", "r", stdin);
#endif
    return 0;
}

使用const定义常量,而非def

使用const好处在于,可以确定变量的类型,而不是单纯的一段代码。

浮点数陷阱

该程序是一个死循环 -- i不可能直接==10,最好的方法是fabs(i-10) < 1e-5

c#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
    double i;

    /* 这样是可以的 */
    double z = 10l;
    if(10 == z)
        puts("Yes");

    puts("press any key to continue...");
    system("read a");


    /* 这样也行 */
    for(i = 0; i != 10; i+=0.1)
    {
        /* printf("%.1lf\n", i); */
        printf("%lf\n", i);
        if(fabs(i - 10) < 1e-5)
            break;
    }

    puts("press any key to continue...");
    system("read a");

    /** 这样不行 **/
    for(i = 0; i != 10; i+=0.1)
    {
        /* printf("%.1lf\n", i); */
        printf("%lf\n", i);
        if(i == 10)
        {
            puts("yes");
            break;
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值