zoukankan      html  css  js  c++  java
  • 随机生成数据 文件数据的输入输出

    **以下代码的用途是:
    生成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("
    ");
        }
    
        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
    ");
            exit(0);
        }
        if(freopen("test.out","w",stdout)==NULL)
        {
            printf("FEIL OPEN ERROR
    ");
            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]!=''; i ++)
                sum += (str[i]-'0')*num[j++];
            printf("%d
    ",sum);
        }
        if(fclose(stdin))
        {
            printf("FEIL CLOSE ERROR
    ");
            exit(0);
        }
        if(fclose(stdout))
        {
                printf("FEIL CLOSE ERROR
    ");
            exit(0);
        }
        return 0;
    }
  • 相关阅读:
    pyqt动画的使用
    pyqt 自定义信号
    设计工具- QtDesigner
    样式控制-QSS 样式表
    布局管理之 QStackedLayout (堆 布局)
    布局管理之 QGridLayout (网格布局)
    布局管理之 QFormLayout (表单布局)
    看代码中
    公司同事好坑
    我要多开梦幻手游PC端(梦幻手游PC端多开的简单分析及实现办法)
  • 原文地址:https://www.cnblogs.com/hellocheng/p/7350160.html
Copyright © 2011-2022 走看看