-
Nov 24th, 2015, 07:35 PM
#1
Thread Starter
Member
Help on Assignment!
So I need to make this program so that it calculates using pointers instead of subscrpits. this is what I have done but it wont work.
Code:
// rain.c -- finds yearly totals, yearly average, and monthly average for several years of rainfall data*
#include <stdio.h>
#define MONTHS 12 // number of months in year
#define YEARS 5 // number of years of data
int main(void)
{
// initializing rainfall data for 2010 - 2014
const float rain[YEARS][MONTHS]=
{
{4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
{8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,3.0,0.9,1.4,7.3},
{9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4},
{7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2},
{7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2},
};
int year, month;
float subtot, total;
/*my pointer to rain[YEARS][MONTHS]*/
const float (*myRain)[2];
/*assign rain[][] to myRain pointer*/
myRain = rain;
printf("YEAR RAINFALL (inches)\n");
for (year= 0, total = 0; year < YEARS; year++)
{ //for each year, sum rainfall for each month
for (month = 0, subtot = 0; month < MONTHS; month++)
subtot += rain[year][month];
/*pointer to rain*/
subtot += *(*(myRain + year) + month);
printf("%5d %15.1F\n",2010 + year, subtot);
total += subtot; // total for all years
}
printf("\nThe yearly average is %,1f inches.\n\n",
total/YEARS);
printf("MONTHLY AVERAG:\n\n");
printf("JAN FEB MAR APR MAY JUN JUL AUG SEP OCT");
printf("NOV DEC\n");
for (month =0; month < MONTHS; month++)
{ // for each moth, sum rainfall over years
for (year = 0, subtot = 0; year < YEARS; year++)
subtot += rain[year][month];
printf("%4,1f", subtot/YEARS);
}
printf("\n");
return 0;
}
-
Nov 25th, 2015, 09:30 AM
#2
The best argument against democracy is a five minute conversation with the average voter - Winston Churchill
Hadoop actually sounds more like the way they greet each other in Yorkshire - Inferrd
-
Dec 3rd, 2015, 09:58 AM
#3
Re: Help on Assignment!
Code:
const float (*myRain)[2];
Why 2?
Code:
subtot += *(*(myRain + year) + month);
This also doesn't seem right. myRain is a pointer so you are setting the pointer according to the year then doing a deference from this memory address to get a value (as dereference has higher precedence than addition) then adding month to this value and treating this as a memory pointer and doing another dereference ??
Last edited by 2kaud; Dec 3rd, 2015 at 12:59 PM.
All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/
C++23 Compiler: Microsoft VS2022 (17.6.5)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|