首页 > 解决方案 > 计算平均海平面变化

问题描述

这是我正在尝试做的任务。从http://climate.nasa.gov/vital-signs/sea-level下载海平面数据(链接到外部站点。)。创建一个执行以下操作的程序:

一个。告诉用户该程序使用来自 NASA 的数据来预测 2020 年至 2050 年的海平面。

湾。将海平面数据存储在数组中。从 1993 年到现在,您每年只需使用一个数据点。使用每一行的最后一列(去除了年度和半年度信号的全球平均海平面 GMSL)。

C。找出数据中指定的所有年份中海平面的平均年变化。(提示 - 使用循环将多年来的年度变化存储在数组中,然后使用循环计算平均年度变化)。

d。假设线性增加并计算 2020、2025、2030、2035、2040、2045 和 2050 年的预测海平面上升。将这些结果存储在它们自己的数组中。(提示 - 只需使用您在 c 部分计算的平均值作为未来几年的年度变化)。

e. 为用户显示结果并确保引用数据文件中指定的数据集,以便用户知道数据的来源。

样本输出:

预测的全球平均海平面为

2020 年 64.32

2025 年 68.98

2030 年 73.51

2035 78.12

2040 83.43

2045 88.12

2050 93.04

这些预测是使用 XXXXXXXXXX 提供的数据做出的

这是到目前为止的代码。然而,它似乎没有使用数组中的所有数据来找到海平面的平均变化。

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

int main()
{
//creates a file object to read data
FILE* infile = fopen("nasa.txt","r");

//checks if file exists
if(infile == NULL)
{
printf("File does not exist.\n");
return -1;
}

//create 2d array to store years and their sea levels
int level[50][2];
//number of elements in array
int n = 0,i;

char word[5];

//read data from file word by word
while(fscanf(infile, "%s", word) != EOF)
{
if(word != ' ' && word != '\n')
{

//convert string to int and store in array
level[n][0] = atoi(word);

//store sea level
fscanf(infile, "%s", word);
level[n][1] = atoi(word);

//increment n
n++;
}
}

//store avg change
float avg=0;

for(i=1;i<n;i++)
{
//add difference of consecutive elements
avg += level[i][1] - level[i-1][1];
}

//calculate mean
avg = (float)avg/n;

int c = 7; //number of predictions
//array to store results
float predictions[][2] = {{2020,0},{2025,0},{2030,0},{2035,0},
{2040,0},{2045,0},{2050,0}};


//predict future sea levels
for(i=0;i<c;i++)
{
//multiply avg change by number of years
predictions[i][1] = level[n-1][1] +
(predictions[i][0] - level[n-1][0])*avg;
}

//print avg change
printf("Average change in sea level year over year is: %f mm\n",avg);

//print predictions
for(i = 0;i<c;i++)
{
printf("Predicted sea level change since 1993 for the year %.0f: %.2f mm\n",
predictions[i][0],predictions[i][1]);
}
printf("These predictions were made using data provided by the National Aeronautics and Space Administration.");

return 0;
}

海平面变化数据

1993 4

1994 7

1995 11

1996 14

1997 21

1998 20

1999 19

2000 22

2001 27

2002 31

2003 34

2004 36

2005 40

2006 42

2007 43

2008 47

2009 48

2010 54

2011 53

2012 59

2013 65

2014 68

2015 75

2016 83

2017 85

2018 88

2019 94

标签: c

解决方案


然而,它似乎没有使用数组中的所有数据来找到海平面的平均变化。

avg = (float)avg/n;与 相同avg = (float)(level[n-1][1] - level[0][1])/n

只有终点很重要。
累积差异的循环正在消除中间年份的值。

年中加+100,一年差+100,下一年差100。最终的+100不会影响差异的运行总和。

所有的年中值都可能是 0 并且其中一个会得到相同的平均值


推荐阅读