Answer to Question #49712 in C++ for nada

Question #49712
Write a function called nRandomNumbers( ) that
 Generates N random integers between -250 and 250 (inclusive) and saves them in a file
called number.txt, (Use the function srand()).
 Prints all the generated integers.
 Finds the average of all the negative integers, and the maximum of all the positive
integers.
 Returns the the average.
Then, write a main program that
 Prompts the user to input the value of N.
 Calls the function nRandomNumbers( ).
 Prints the average of all the negative integers.
1
Expert's answer
2014-12-05T01:25:02-0500
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>

float nRandomNumbers(int N, int min,int max,char *fname)
{
float maxPositive=-1,averageNegative=0;
int nNegative=0;
int number,i;
srand (time(NULL));
FILE *f;
f=fopen(fname,"wt");
for(i=0;i<N;i++)
{
number=rand()%(max-min)+min;
fprintf(f,"%d\n",number);
if(number>0)
{
if((maxPositive<0)||(maxPositive<number))
maxPositive=number;
}
if(number<0)
{
averageNegative+=number;
nNegative++;
}
}
fclose(f);
if(nNegative>0)
return 1.*averageNegative/nNegative;
else
return 0;
}

int main()
{
int N;
cout<<"Input N:";
cin>>N;
float res=nRandomNumbers(N,-250,250,"number.txt");
cout<<"Average of all thenegative integers: "<<res;
getch();
return 0;
}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS