随机生成数据 文件数据的输入输出

**以下代码的用途是:
生成1000个长为150二进制串,将每个二进制串输出到test.in文件里**

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

int main()
{
    freopen("test.in","w",stdout);
    //用"w"打开的文件只能向该文件写入。若打开的文件不存在,则以指定的文件名建立该文件,若打开的文件已经存在,则将该文件删去,重建一个新文件。
    srand((unsigned)time(NULL));
    //设置种子
    int i,n,sum,num[300],k,j;
    for( j = 1; j <= 1000; j ++)
    {
        for( i = 1; i <= 150; i ++)
        {
            n = rand()%2;//生成随机二进制数
            num[i] = n;
        }
        for( i = 150; i >= 1; i --)
            printf("%d",num[i]);//将二进制串输出到文件中
        printf("\n");
    }

    return 0;
}

rand()函数用来产生0~32767的随机数,srand()用来设置rand()产生随机数时的随机数种子,如果没有用srand()函数设置随机数种子,随机数种子将自动设成相同值1,这将导致rand()所产生的随机数值都一样。使用time()函数,要包含头文件time.h

以下代码的用途是
从已经生成数据的test.in文件里读入数据,再将程序执行后的数据输出到文件 test.out里
和平时二进制转十进制基数为2不同,在该题中二进制字符串从右到左对应素数序列2,3,5。。。。输出转换结果。


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

int  prime(int n)
{
    int i;
    if( n == 1||n==0)
        return 0;
    for( i = 2; i*i <= n; i ++)
    {
        if(n%i == 0)
            return 0;
    }
    return 1;
}

int main()
{
    if(freopen("test.in","r",stdin)==NULL)
    {
        printf("FEIL OPEN ERROR\n");
        exit(0);
    }
    if(freopen("test.out","w",stdout)==NULL)
    {
        printf("FEIL OPEN ERROR\n");
        exit(0);
    }
    int i,j= 0, l;
    int num[1000],sum;
    char str[200];
    for( i = 1; i <= 1000; i ++)
    {
        if(prime(i))
            num[j++] = i;

    }
    while(scanf("%s",str)!=EOF)
    {
        j = 0;
        sum = 0;
        for(i = 0; str[i]!='\0'; i ++)
            sum += (str[i]-'0')*num[j++];
        printf("%d\n",sum);
    }
    if(fclose(stdin))
    {
        printf("FEIL CLOSE ERROR\n");
        exit(0);
    }
    if(fclose(stdout))
    {
            printf("FEIL CLOSE ERROR\n");
        exit(0);
    }
    return 0;
}

转载于:https://www.cnblogs.com/hellocheng/p/7350160.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值