jyfcxhn 发表于 2020-4-21 10:10:05

关于文件创建、数据输入以及数据计算的问题

首先创建文件111.txt,数据分别是12 23 44 68 95 68 47 95 10 25
编写程序,求出该数据文件中,在第3个-第9个数据之间,能被2整除的最大值。

liuzhengyuan 发表于 2020-4-21 10:13:55

本帖最后由 liuzhengyuan 于 2020-4-21 10:17 编辑

先文件输入,字符串读入,然后 split 分开
用列表切片,筛选出 第 3~9 个 数
然后再用 map + lambda 筛选所有能被 2 整除的数
然后求用 max() 出最大值

qiuyouzhi 发表于 2020-4-21 10:13:57

直接读出来,用split分割然后遍历就好了。

sunrise085 发表于 2020-4-21 10:23:47

#include<stdio.h>

int main()
{
    FILE *fp;
    int n,i=0,max=0;
    char ff = "12 23 44 68 95 68 47 95 10 25";
    fp = fopen("111.txt","w");
    fputs(ff,fp);
    fclose(fp);

    fp = fopen("111.txt","r");
    while(fscanf(fp,"%d",&n)==1)
    {
      i++;
      if(i>=3 && i<=9)
            if (n%2==0 && n>max)
                max=n;
    }
    printf("%d",max);
    fclose(fp);
    return 0;
}

sunrise085 发表于 2020-4-21 10:31:36

呃,不好意思。刚刚看成C语言了
现在的是python版本
f=open("111.txt","w")
f.write("12 23 44 68 95 68 47 95 10 25")
f.close()
f=open("111.txt","r")
str1=f.readline()
num=list(map(int,str1.split(" ")))

max=0
for i in num:
    if not i%2 and i>max:
      max=i
print(max)

sunrise085 发表于 2020-4-21 10:34:41

sunrise085 发表于 2020-4-21 10:31
呃,不好意思。刚刚看成C语言了
现在的是python版本

这样更好。
因为不能保证max就一定大于0,所以max赋初值就可能会出错
f=open("111.txt","w")
f.write("12 23 44 68 95 68 47 95 10 25")
f.close()
f=open("111.txt","r")
str1=f.readline()
num=list(map(int,str1.split(" ")))

ood=[]
for i in num:
    if not i%2:
      ood.append(i)
print(max(ood))

jyfcxhn 发表于 2020-4-21 11:20:22

谢谢&#128513;&#128513;

jyfcxhn 发表于 2020-4-21 11:49:54

运行成功了!谢谢
&#128513;&#128513;&#128513;

sunrise085 发表于 2020-4-21 15:14:01

jyfcxhn 发表于 2020-4-21 11:49
运行成功了!谢谢
&#128513;&#128513;&#128513;

那就给个最佳答案吧

永恒的蓝色梦想 发表于 2020-4-21 15:31:39

sunrise085 发表于 2020-4-21 15:14
那就给个最佳答案吧

又是个喜欢白嫖的{:10_262:}

jyfcxhn 发表于 2020-4-22 15:01:23

sunrise085 发表于 2020-4-21 15:14
那就给个最佳答案吧

嗯嗯,已经设定了,谢谢啦
页: [1]
查看完整版本: 关于文件创建、数据输入以及数据计算的问题