I have a program that can generate a random integer every 1/10 second.
Here is the code:
int main()
{
ofstream myfile;
int max;
cout << "Max number: ";
cin >> max;
for (int i = 0; i < max; ++i)
{
myfile.open("test.txt",fstream::app);
myfile << random_int() << "\n";
myfile.close();
this_thread::sleep_for(chrono::milliseconds(100));
}
return 0;
}
int random_int()
{
return rand() % 10;
}
Now the question is, I need to write a program that calculate then output the average in the same rate. If the output of the number generator is:
1
2
3
4
5
The output of the average calculator should be
1
1
2
2
3
Every 1/10 second the program will output a number.
Note: The max number could be from 0 to couple millions. Calculating the average by adding all previous number during the time interval won't be ideal.
I am a sophomore student and a research assistant in a university. This is a simplified version of a problem that I encounter currently. Any suggestion will be greatly appreciated.
Update: Thanks for the help from Fei Xiang and oklar. Yes, remember the previous sum is the only way to make the calculation in time. However, since the random generator output file is changing constantly and the new output is appended to the old outputs, I am not sure how to get the most current data efficiently.
You don't need to calculate all the numbers that has been added each time, you only need to add the last one to a sum variable and divide by the amount of generated numbers.
Say you have:
1
2
3
4
5
Sum variable is 15. If you divide by the amount of numbers which is 5, you'll get the expected output of 3. Continuing, add the number 9 for instance to the sum variable and divide by the amount of generated numbers 6, you'll end up with an average of 4.
The i in your for loop can be used as a counter for the amount of generated numbers. Pseudo code:
sum += randomInt();
avg = sum/i;
EDIT:
I see that you are opening and closing the file each time in the for loop in your post. This can be done outside the loop, which will speed things up. If I understand you correctly, your mission is to generate a random number then calculate the average from the previous numbers and finally append it to the text file? If so, you're on point.
int i_random;
int avg;
int sum = 0;
myfile.open("avg.txt",fstream::app);
for (int i = 1; i < max + 1; ++i)
{
i_random = random_int();
sum += i_random;
avg = sum/i;
myfile << avg << "\n";
this_thread::sleep_for(chrono::milliseconds(100));
}
myfile.close();
See http://www.cplusplus.com/doc/tutorial/files/ for other operators. Check out cppreference for seek and tell if you want to skip to a position in the file.
Related
For Example: Input: 982
Outputs: 9 8 2
Your Total sum is: 19
I see people using input_number % 10 in a loop and then input_number / 10 but I still do not get it. If i did 982 % 10 I would get 2 and then they add it to the sum which is 0 + 2 = 2 and how would that get 19???? and then the input number which is 982/10 is equal to 9.82 how does lead me to my solution of 19?? I am just super confused can someone please explain it to me and try to work out the problem and make it into a simple solution. I appreciate it and try to use the basic stuff like including namespace std and then not using arrays just loops and simple math equations thank you.
int n,sum=0;
cin>>n;
while(n!=0)
{
sum=sum+(n%10);
n=n/10;
}
/*
Since your n is an integer it will drop the value after decimal.
Therefore, 982 will run as
Iteration 1 n=982
sum=2
n=982/10=98
Iteration 2
sum=2+(98)%10 = 10
n=98/10= 9
Finaly in iteration 3
n=9/10=0 hence loop will terminate and sum be 19*/
You should input the number as a characters, that you convert into the digits and then individual numbers, that are easy to add or print or whatever. Avoid complicated math when you can totally live without it.
std::string str;
std::cin >> str;
int sum = 0;
for( int i=0; i<str.length(); i++) {
if( isdigit(str[i]) ) {
std::cout << str[i] << " ";
sum += int(str[i] - '0') // convert a char to int
}
}
std::cout << std::endl;
std::cout << "Total sum: " << sum << std::endl;
or something like that. Haven't programmed in C++ for a while, there might be minor mistakes in the code, but you get the general idea.
I need help figuring out where my code went wrong. I want to reset the values for the loop so that it isn't compiling because my output right now is using past input values in current calculation whereas I want the output to be different every time as though it is the firs time running the code. The code works fine when I don't use the while loop, but then I have to rerun the program each time. I want the output to prompt a new input every time, but not use past inputs in the new calculations. I know I'm not explaining it very well, but I'm just sort of lost. Anything helps!
This is my problem:
An approximate value of pi can be calculated using the series given
below:
pi = 4 · [ 1 – 1/3 + 1/5 – 1/7 + 1/9 ... + (–1 ^ n)/(2n + 1) ]
Write a C++ program to calculate the approximate value of pi using
this series. The program takes an input n that determines the number
of terms in the approximation of the value of pi and outputs the
approximation. Include a loop that allows the user to repeat this
calculation for new values n until the user says she or he wants to
end the program.
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
int n;
double sum=0;
cout << "Enter the number of terms to approximate (or zero to quit):\n";
cin >> n;
if (n == 0)
{
return 0;
}
while (n != 0)
{
{ for(int i=0;i<n;i++)
{
if (i%2==0)
{
sum += 1.0/(2*i+1);
}
else
{
sum += -1.0/(2*i+1);
}
}
cout.setf(ios::showpoint);
cout.precision(3);
cout << "The approximation is " << sum*4 << " using " << n << " terms." << endl;
}
cout << "Enter the number of terms to approximate (or zero to quit):\n";
cin >> n;
}
return 0;
}
This is my output:
This is what the output should be:
You do not reset sum before entering the for loop. Just add
sum=0;
before the for line.
Notice that 2.67 = 6.67 - 4.00.
You want your program to compute a sum for several values of n.
The sum must be initialized to 0 at the beginning of each calculation, inside the while loop.
Actually, it should even be declared there.
C++ doesn't require you to define variables at the start of a function, so it is perfectly legal to write:
while (n != 0)
{
double sum = 0.0;
this would solve your problem. Alternatively, if you want to keep the declaration of sum at the top of the function, just change your code to
while (n != 0)
{
sum = 0.0;
Here's the important part of my code:
int realnum, positive = 0, total, poscount;
for (poscount = 1; poscount < 11; poscount++)
{
cin >> realnum;
while (realnum > 0)
{
total = realnum + positive;
}
}
cout << "Total of 10 positive values is " << total << endl;
I really just don't see what's wrong here. After declaring my integers the program goes into my for, increase the poscount to 2, asks my to input realnum. I put in a positive number (ex: 6), which should in theory add my realnum with positive (which I declared 0) and give total the value (ex: 6 + 0 = 6). It should keep looping until poscount reaches 11 and output the total of 10 positive numbers.
When I run it, I put in 6 and the command prompt just shows 6, nothing happens, and I have to close through the x button. Can someone please tell me what the error is?
I would just use a while in the outer loop, to keep the number of so-far positive numbers.
Also, your total is uninitialised and you assign positive to it, which is just 0?
This is what I have in mind:
int realnum, total = 0, poscount = 0;
while (poscount < 10) {
cin >> realnum;
if (realnum > 0)
{
total += realnum;
poscount++;
}
}
cout << "Total of 10 positive values is " << total << endl;
Replace your while with an if since currently, once you enter that while loop you never exit it.
Also, why are you always increasing poscount? Shouldn't you only do that if realnum is positive? The iteration statement in the for loop is allowed to be blank; then you write poscount++ inside the new if block.
You also need to write total += to increment the total amount.
These things are easy to spot if you use your debugger.
Okay, so I think I've corrected myself (without blatantly copying blurry but also using Bathsheba's tip on replacing my while.
int realnum = 1, positive = 0, total, poscount;
if (realnum > 0)
{
for (poscount = 1; poscount < 11; poscount++)
{
cin >> realnum;
total = realnum + positive;
positive = total;
}
}
cout << "Total of 10 positive values is " << total << endl;
So far, it seems to work, there's probably a lot of unnecessary things that make it inefficient but I didn't want to copy examples. *Edit of course I still need to do with the ignoring negative part
I think I backed myself into the point of no return, ha. I really thought there was an alternate way I was going... Anyways, thanks for your replies, guys. I've always been lurking around here, until I made an account now.
Add a condition to terminate the while loop. And instead of adding positive to realnum, try adding poscount. That should provide the desired result.
I was wondering if anyone can help me with something I was struggling all day with.
In the code below I dictated an array of randomized numbers from which I have to have pull out the max the min and the average. It all looks fine and good (such a compact software!) But I attain a weird output. I believe I have a finger on what the problem is (say I'm finding the max for the first number but the next number is smaller the software will think that's the biggest number even though integer 14 may be bigger) but I have no idea how to go about fixing this. The minimum value I have no idea why it's wrong it keeps saying it's zero and the average value stays anywhere from 10-19 which is impossible considering the range of randomized numbers goes from 1 to 1000. I was never taught how to organize random numbers in an array, so I just have no idea how to go about fixing this. Any help will be super awesome! I really struggled with this program and even scrapped it multiple times, if it's only a simple mistake I overlooked I would feel awfully embarrassed I'll post the code and an example output below.
Thanks for taking your time, I hope you have a wonderful day!
#include <cmath>
#include <iostream>
#include<cstdlib>
#include <ctime>
#include <time.h>
#include <iomanip>
using namespace std;
int main()
{
//Defining variables
//DEFINE SIZE
const int ARRAY_SIZE =20;
//Index variable
int i;
//For finding average
double sum=0;
double max_value;
double min_value;
//Keep all numbers sane
cout.precision(5);
srand((unsigned)time(0));
double main_array[ARRAY_SIZE];
//Header
cout << "Element number \t\t" << "Random Number\n\n" << endl;
//Assigning random values into array.
for (i=0; i< ARRAY_SIZE; i++)
{
max_value=0;
min_value=0;
//Randomizer
double ran = 0 + (rand()/((float)RAND_MAX/(1000-0)));
main_array[i] = ran;
cout << "\t" << i << "\t\t" << main_array[i] << endl;
//Find average
sum= (sum + main_array[i]);
sum= sum/(ARRAY_SIZE+1);
//Initalizing
for (int i = 0; i < ARRAY_SIZE; i++)
{
if ( min_value > ran)
min_value = main_array[i];
if (max_value < ran)
max_value = main_array[i];
}
}
cout <<"Average Value is: " << sum << endl;
cout <<"\nThe Minimum Value Is: " << min_value << endl;
cout <<"\nThe Maximum value Is: " << max_value << endl;
system ("pause");
return 0;
}
An output example would be
Element number Random Number
0 791.62
1 542.04
2 879.57
3 875.39
4 38.057
5 73.702
6 973.27
7 22.431
8 830.26
9 444.59
10 276.89
11 888.12
12 827.17
13 900.45
14 883.72
15 201.15
16 317.64
17 649.83
18 443.98
19 683
Average Value is: 33.603
The Minimum Value Is: 0
The Maximum value Is: 791.62
Press any key to continue . . .
Unless you must do otherwise, use std::min_element to find the minimum, std::max_element to find the maximum, and std::accumulate to find the sum.
If you absolutely must do this on your own, you usually want to initialize your minimum and maximum to the first element in the collection, then look for others that are smaller/larger:
int mininum = array[0];
int maximum = array[0];
for (int i=1; i<array_size; i++) {
if (array[i] < minimum)
minimum = array[i];
if (array[i] > maximum)
maximum = array[i];
}
Before you start looping, create a min, max, and total. Then when you are creating each element of the array, also check whether it is less than the min or more than the max. Also add that number to your total. At the end, outside the loop, divide the total by the number of elements to get your average.
You definitely shouldn't be iterating through the whole array each time you add an element, and you shouldn't be resetting your min and max each time through the loop. You also shouldn't set your min to 0 if all your numbers are going to be more than 0, because it will never be updated.
I'm Having problems with to of the questions on my C++ homework.
Write a program to analyze gasoline price in the past 10 days. First, ask the user to enter the prices. Then do the following:
(a) Calculate and display the average price in the first 5 days and the average price in the second 5 days
(b) Compare the two average prices. Determine and report which one is higher (or they are the same).
(c) Compare each day’s price (except day 1) with the price the day before. Determine whether it became higher, lower or remained the same. Count and report the number of days the price was higher than, lower than and the same as the price the day before, respectively.
i'm not sure how to compare how to compare the first five days with the last five days, and part c I'm completely lost on....
i'm not looking for someone to do my homework for me, but a push in the right direction would be a great help!
here is what I have made so far:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
double gasPrice[10];
double firstFive = 0.0;
double lastFive = 0.0;
double ffAvg = 0.0;
double lfAvg = 0.0;
for (int x = 0; x < 10; x = x + 1)
{
gasPrice[x] = 0.0;
}
cout << "You will be asked to enter daily gas prices for 10 days."<< endl;
ofstream gasprice;
gasprice.open("gasprice.txt", ios::app);
if (gasprice.is_open())
{
for (int x = 0; x < 10; x = x + 1)
{
cout << "Enter the gas price " << x+1 << ": ";
getline(cin, gasPrice[x];
}
if ( ffAvg > lfAvg)
{
cout << "The first five days have a lower gas price " << ffAvg << lfAvg << endl;
}
else if ( ffAvg < lfAvg)
{
cout << "The last five days have a lower gas price " << ffAvg << lfAvg << endl;
}
system("pause ");
return 0;
}
Read the requirements like they are a description rather than a computer formula. It can become overwhelming when learning something for the first time and we get drowned by the things that would come natural in another environment.
Anyway, you are not to compare the days individually but an AVERAGE of the days. So you first need to compute the AVERAGE of the first five and the AVERAGE of the second five days, then compare that.
For the second part of your question, aggregators for your totals is the push I would give you.
Hope this helps.
Break down the problem in to a series of stages: Firstly, you need to get 10 input prices from the user, and store them in an array of size 10.
Next, you need to compute the average price for the first five days (i.e. for values in index 0-4 of your array), and store it in ffAvg, you can do this using the following simple for loop:
double sum;
for( int i = 0; i < 5; i++ )
{
sum += gasPrice[i];
}
double ffAvg = sum / 5;
You then do this with the 2nd 5 days, storing the average in lfAvg.
The next part of your task is to compare the averages, you can doing this using if and else if statements, for example, if you wanted to compare to numbers, num1 and num2 you might do the following:
if( num1 > num2 )
{ /* Do something */ }
This will compare num1 and num2 and if num1 is greater than num2 it will perform the code in the braces.
To do the last comparison you simply combine what we have done above on a per day basis. Try to experiment with various ways of doing it, as this will help you to learn more.
Hope this helps you! :)
EDIT: I also noticed that you've not closed a lot of your bracers, you must always do this so the compiler can work properly. Every { must have a corresponding }, else the compiler should throw up errors, and not compile.
I sugest doing as following:
double average1=0.0;
for(int i=0;i<5;++i) {
average1 += values[i];
}
average1/=5.0;
double average2=0.0;
for(int i=5;i<10;++i) {
average2 += values[i];
}
average2/=5.0;
Also, take a look at std::vector, it may help you in further exercises:
http://www.cplusplus.com/reference/stl/vector/
You should first compute the average of the first and last 5 days. The average is defined by the sum divided by the number of items. So your average will be (gasPrice[0] + gasPrice[1] + gasPrice[2] + gasPrice[3] + gasPrice[4]) / 5.0.
You should probably make this computation in a loop similar to the one you have for getting the input. The loop should only iterate 5 times.