C语言文件读写实现字典序算法

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAX 10

//c(m,n)
int combinatorial(int m,int n)
{
    int result=1;
    for(int k=1;k<=n;k++)
    {
        //if m<n,exist m,n,k make m-n+k=0
        result=(result*(m-n+k))/k;//先算乘法,避免先算(m-n+k)/k除不尽带来误差
    }
    return result;
}

int solution(char *str)
{
    int result=0;
    int l=strlen(str);
    for(int i = 1; i <= l; i++)
        result += combinatorial(26, i);
    for(int i = 0; i < l; i++)
        result -= combinatorial(26-(str[i]-'a'+1), l-i);
    return result;
}

int main()
{
    FILE *in_fp , *out_fp;
    char **str;
    char temp[MAX];

    in_fp= fopen("input.txt", "r");
    if(in_fp == NULL)
    {
        printf("Open file Error!");
        exit(0);
    }

    //read first line
    fgets(temp, MAX, in_fp);
    int num = atoi(temp);

    str=(char **)malloc((num)*sizeof(char *));
    for(int j=0;j<num;j++)
    {
        str[j]=(char*)malloc(sizeof(char)*MAX);
    }      

    //sprintf(str[0], "%d" , num);

    int i=0;  

    while(fgets(str[i], MAX, in_fp) != NULL)
    {
        if(str[i][strlen(str[i])-1] == '\n')
            str[i][strlen(str[i])-1] = '\0';
        i++;
    }
    fclose(in_fp);

    out_fp= fopen("output.txt", "w");

    char **list=(char**)malloc((num)*sizeof(char*));
    for(int j=0;j<num;j++)
    {
        list[j]=(char*)malloc(sizeof(char)*MAX);
    }      

    for(int i=0;i<num;i++)
    {
        //list[i]=solution(str[i]);
        sprintf(list[i], "%d" , solution(str[i]));
        fputs( list[i], out_fp );
        fputs("\n",out_fp);
    }

    fclose(out_fp);

    for(int k=0;k<num;k++)
    {
        free(str[k]);
        free(list[k]);
    }
    free(str);
    free(list);

    return 0;
}

注:

  • C语言中,对于参数的要求似乎没有C++严格,封装的一些函数的const参数可以由变量输入如list[i]。数组也可以用变量定义维数。
  • 求组合数的方法参考求组合数,直接用阶乘计算会溢出
  • 关于C语言指针的一些小细节
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    char *p=(char*)malloc(100);
    char *q=(char*)malloc(100);


    sprintf(p, "%d" , 1999);
    q=p; //address
    *q=*p;//the first characata of p;
    strcpy(q,p);//only the value
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值