编程从键盘输入10个实型数据存入file1文件中

C语言文件操作示例
本文展示了一个使用C语言进行文件读写的程序实例。通过该程序,用户可以输入10个实数并保存到名为file1.dat的文件中,随后程序会再次读取这些数据并显示出来。此代码涉及文件的打开、写入、关闭及读取等基本操作。
《程序设计基础-c语言》杨莉 刘鸿翔  
ISBN-978-7-03-032903-5  
p257
习题8

3.编程从键盘输入10个实型数据存入file1文件中

#include<stdio.h>
#include<stdlib.h>
int main()
{
    FILE *fp;
    double a[10];
    printf("输入10个实型数据:(eg:1.1 2.3)\n");
    int i;
    for(i=0;i<10;i++)
    {
        scanf("%lf",&a[i]);
    }
    if((fp=fopen("file1.dat","wb"))==NULL)
    {
        printf("file open error\n");
        exit(0);
    }
    for(i=0;i<10;i++)
    {
        if(fwrite(&a[i],sizeof(double),1,fp)!=1) printf("write error\n");
    }
    fclose(fp);

    if((fp=fopen("file1.dat","rb"))==NULL)
    {
        printf("file open error\n");
        exit(0);
    }
    for(i=0;i<10;i++)
    {
        fread(&a[i],sizeof(double),1,fp);
        printf("%lf\n",a[i]);
    }
    fclose(fp);
    return 0;
}

在这里插入图片描述

当然,我可以帮助你实现从键盘输入两组数据并分别存入两个数组的功能。以下是一个示例代码,展示了如何实现这一功能: ```c #include <stdio.h> #define SIZE 100 int main() { int array1[SIZE]; int array2[SIZE]; int size1, size2; // 输入第一组数据的大小 printf("Enter the number of elements for the first array: "); scanf("%d", &size1); // 输入第一组数据 printf("Enter the elements of the first array:\n"); for (int i = 0; i < size1; i++) { scanf("%d", &array1[i]); } // 输入第二组数据的大小 printf("Enter the number of elements for the second array: "); scanf("%d", &size2); // 输入第二组数据 printf("Enter the elements of the second array:\n"); for (int i = 0; i < size2; i++) { scanf("%d", &array2[i]); } // 输出第一组数据 printf("The first array is:\n"); for (int i = 0; i < size1; i++) { printf("%d ", array1[i]); } // 输出第二组数据 printf("\nThe second array is:\n"); for (int i = 0; i < size2; i++) { printf("%d ", array2[i]); } return 0; } ``` ### 解释 1. **定义数组大小**: 使用宏定义 `SIZE` 来定义数组的最大大小。 2. **输入数组大小**: 使用 `scanf` 函数从键盘输入每个数组的大小。 3. **输入数组元素**: 使用 `for` 循环和 `scanf` 函数从键盘输入每个数组的元素。 4. **输出数组元素**: 使用 `for` 循环和 `printf` 函数输出每个数组的元素。 这样,你就可以从键盘输入两组数据并分别存入两个数组中了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

折腾的小飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值