你题目的解答代码如下:(如有帮助,望采纳!谢谢! 点击我这个回答右上方的【采纳】按钮)
#include<stdio.h>
int main() {
int n;
FILE *fp;
char c;
printf("---------------菜单-------------\n");
printf("a)找到data.txt中的最大数字\n");
printf("b)计算data.txt中所有正数的平均值\n");
printf("请选择a或b:");
c = getchar();
if (c=='a' || c=='A')
{
int max;
fp = fopen("data.txt", "r");
fscanf(fp, "%d", &max);
while (fscanf(fp, "%d", &n)>0)
{
if (n>max)
max = n;
}
fclose(fp);
printf("最大数字:%d",max);
}
else
{
float sum=0,avg;
int i=0;
fp = fopen("data.txt", "r");
while (fscanf(fp, "%d", &n)>0)
{
if (n>0) {
sum += n;
i++;
}
}
avg = sum/i;
fclose(fp);
printf("所有正数的平均值%.3f",avg);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *ReadFile(char *path, int *length)
{
FILE *pfile;
char *data;
pfile = fopen(path, "r"); //open as binary
if (pfile == NULL)
{
return NULL;
}
fseek(pfile, 0, SEEK_END); //读取文件长度
*length = ftell(pfile);
data = (char *)malloc((*length + 1) * sizeof(char));
rewind(pfile);
*length = fread(data, 1, *length, pfile);
data[*length] = '\0';
fclose(pfile);
return data;
}
int main(int argc, char const *argv[])
{
char *content;
int data[20] = {0};
int count = 0;
int length;
// char *path = "./input.txt";4
char *path = "F:\\Ctest\\input.txt";
char *p;
content = ReadFile(path, &length); //字符串形式的input内容
p = strtok(content, " "); //初次分割
while (p)
{
data[count] = atoi(p);
// printf("%d\n",data[count]); 此模块已经写好,现在data的前16项为对应数字了
++count;
p = p = strtok(NULL, " "); //继续分割
}
// printf("%d\n", count);
int choice;
printf("enter 1 for mode 3a;\nenter 2 for mode 3b.\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
{
int max = data[0];
for (int i = 1; i < count; i++)
{
if (data[i] > max)
{
max = data[i];
}
}
printf("max number in txt is %d.\n", max);
break;
}
case 2:
{
float average = 0.0;
int positive_count = 0;
for (int i = 0; i < count; i++)
{
if (data[i] > 0)
{
positive_count++;
average += data[i];
}
}
average /= positive_count;
printf("the average number of all positive numbers is %f\n", average);
}
break;
default:
printf("Invalid option!\n");
break;
}
return 0;
}