I'm trying to calculate simple MA by reading values from a file.
The values are stored like this:
11
12
13
14
15
16
17
I've did this so far:
for (int i = 0; (ifs); i++) {
ifs >> price;
//cout << "price:" << price;
prices_vec.push_back(price);
sum += prices_vec[i];
cnt++;
if (cnt >= 5) {
output_file << sum / 5 << endl;
cout << "Your SMA: " << (sum / 5) << endl;
sum -= prices_vec[cnt - 5];
}
}
This works, but at the end, it adds two additional numbers in the end. The output in file is:
13
14
15
15.8
0
Any idea why this might be happening? And, is there a more efficient way to calculate SMA?
I believe this will solve your problem:
int main()
{
int cnt = 0, sum = 0;
vector<float> prices_vec;
std::ifstream ifs ("Nos.txt", std::ifstream::in);
float price;
for (int i = 0; (ifs) >> price; i++) {
prices_vec.push_back(price);
sum += prices_vec[i];
cnt++;
if (cnt >= 5) {
cout << sum / 5 << endl;
cout << "Your SMA: " << (sum / 5) << endl;
sum -= prices_vec[cnt - 5];
}
}
return 0;
}
Related
I want to find Maximum numbers from my "numbers.txt" file and amount of negative numbers. And i want to output the Total result to another .txt file and console and the rest to the console only.
Im very new and just cant figure out how to do it.
This is what i have now
a "numbers.txt" file with
-4
53
-5
-3
2
and
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n = 0;
int sum = 0, total = 0;
fstream file("numbers.txt");
while (file >> n)
{
sum += n;
total++;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
int Highest;
int Negative;
cout << "Total result: " << sum << endl;
cout << "Numbers added: " << AmountOfNumbersAdded << endl;
cout << "Average number: " << average << endl;
cout << "Maxiumum number: " << endl;
cout << "Negative numbers: " << endl;
return 0;
}
i tried to do
float Highest = INT_MIN;
if (Highest < num[i]) {
Highest = num[i];
but it just wouldn't work.
You don't need to store the numbers to find the maximum or the amount of negative numbers, but you need to track them inside the loop, like you're already doing with the sum and the total amount of numbers.
int Highest = INT_MIN;
int Negative = 0;
while (file >> n)
{
sum += n;
total += 1;
if (n < 0)
{
Negative += 1;
}
if (n > Highest)
{
Highest = n;
}
}
float average = (float)sum / total;
Here's what you're looking for.
#include <iostream>
#include <fstream>
int main()
{
int n = 0;
int sum = 0, total = 0;
int highest = 0;
int negatives = 0;
std::fstream file("numbers.txt");
while (file >> n)
{
if (n > highest) highest = n;
if (n < 0) ++negatives;
sum += n;
++total;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
std::cout << "Total result: " << sum << "\n";
std::cout << "Numbers added: " << AmountOfNumbersAdded << "\n";
std::cout << "Average number: " << average << "\n";
std::cout << "Maxiumum number: " << highest << "\n";
std::cout << "Negative numbers: " << negatives << "\n";
file.close();
return 0;
}
As you're new, few advices for you:
Never use using namespace std.
Prefer using "\n" instead of std::endl.
Don't forget to close any files/database after opening them like you did in your code.
Always try to avoid macros.
#include <iostream>
using namespace std;
int main()
{
int n, G;
float num[500], sum=0.0, average,Grades;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 500 || n <= 0)
{
cout << "Error! number should in range of (1 to 500)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(G = 0; G < n; ++G)
{
cout << G + 1 << ". Enter number: ";
cin >> num[G];
sum += num[G];
}
average = sum / n;
Grades = num[G] >= average;
cout<<endl;
cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average : " <<Grades<< endl;
cout << "Number of grades above the Average = "<<(int) Grades;
return 0;
}
i coded this code but the Number of grades above the Average and Grades above or equal the Average don't work it just print 0
i tried to print the Grades >= the avg but it print 0
also num of Grades also print 0
where is the error ?
I think you was trying to do something like this:
...
int grades_on_avg, upper_grades = 0;
for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
for(int i = 0; i < n; ++i) // use separate for loop and redefined index
{
if(num[i] == average) // compare to average
grades_on_avg++;
else if(num[i] > average) // if bigger than average
upper_grades++;
}
cout<<endl;
cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average =" << (grades_on_avg + upper_grades) << endl;
cout << "Number of grades above the Average = "<< upper_grades ;
You assign boolean value to Grades variable. Also, you refer to element outside of the array: G variable is equal to n after exiting for-loop, but max index you can use is n - 1 (basic programming rule). So, you should change your code into something like this:
...
int avgGrades{0};
int avgAboveGrades{0};
for(int i{0}; i < n; ++i)
{
if(num [i] == average)
{
++avgGrades;
}
else if(num [i] > average)
{
++avgAboveGrades;
}
}
If you prefer more elegant ways of doing so, you can use std::count_if() function but it's more tricky and requires knowledge about lambdas.
I am having troubles with some of the inputs for my addition/multiplication table, and am hoping to find some help towards fixing this. I will begin by posting what I have for the program.
The code is as follows :
#include <iostream>
using namespace std;
void die() {
cout << "BAD INPUT!" << endl;
exit(1);
}
int main() {
const int ADD = 1;
const int MULTIPLY = 2;
const int MAX_SIZE = 20;
int choice = 0, min = 0, max = 0;
cout << "Choose:\n";
cout << "1. Addition Table\n";
cout << "2. Times Table\n";
cin >> choice;
if (!cin) die();
if (choice != ADD and choice != MULTIPLY) die();
cout << "Please enter the smallest number on the table:\n";
cin >> min;
if (!cin) die();
cout << "Please enter the largest number on the table:\n";
cin >> max;
if (!cin) die();
if (min > max) die();
if (max - min >= MAX_SIZE) die();
if (choice == ADD) {
for (int i = 0; i <= max; i++) {
if (i == 0)
cout << '+';
else
cout << i;
cout << '\t';
for (int j = min; j <= max; j++) {
cout << i + j << '\t';
}
cout << '\n';
}
}
if (choice == MULTIPLY) {
for (int i = min; i <= max; i++) {
if (i == min) {
cout << 'X';
else
cout << i;
cout << '\t';
for (int j = min; j <= max; j++) {
cout << i * j << '\t';
}
cout << '\n';
}
}
}
Now, here are the mistakes that I am getting from this code that I cannot seem to resolve. First, when doing the MUlTIPLY table with min = 1, max = 1, I am getting:
X 1
when I should be getting (I believe)
X 1
1 1
Secondly, while doing the MULTIPLY table with min = 1, max = 12, I am getting:
X 1 2 3 4 ... 12
2 2 4 6 8 ... 24
3 3 6 9 12 ... 36
when I should be getting
X 1 2 3 4 ... 12
1 1 2 3 4 ... 12
2 2 4 6 8 ... 24
3 3 6 9 12 ... 36
And finally, when using the ADD table with min = 21, max = 40, I cannot post all of the code since it is such a mess, but basically the columns/rows are as follows:
+ 21 22 23 24 25 ...
5
1
6
2
7
3
8
When obviously, the code should output the rows and columns to be 21 - 40 evenly. As you can see in the last example, my rows are outputting properly, but somehow my columns are a complete, garbled mess.
I have been sitting and staring at this code for awhile, and can't seem to fix these issues at hand. Can anyone help lead me in the right direction? I really appreciate any help and hints :)
Check this out. Might not be fully optimized, but works
if (choice == ADD) {
cout << '+';
for (int i = min; i <= max; i++) {
cout << '\t' << i;
}
for (int i = min; i <= max; i++) {
cout << '\n' << i << '\t';
for (int j = min; j <= max; j++) {
cout << i + j << '\t';
}
}
}
if (choice == MULTIPLY) {
cout << 'X';
for (int i = min; i <= max; i++) {
cout << '\t' << i;
}
for (int i = min; i <= max; i++) {
cout << '\n' << i << '\t';
for (int j = min; j <= max; j++) {
cout << i * j << '\t';
}
}
}
See output here.
#include <iostream>
#include <iomanip>
#include <cstdio>
void die()
{
std::cout << "BAD INPUT!" << "\n";
exit(1);
}
int main() {
const int ADD = 1;
const int MULTIPLY = 2;
const int MAX_SIZE = 20;
int choice = 0, min = 0, max = 0;
std::cout << "Choose:\n";
std::cout << "1. Addition Table\n";
std::cout << "2. Times Table\n";
std::cin >> choice;
if (!std::cin) die();
if (choice != ADD and choice != MULTIPLY) die();
std::cout << "Please enter the smallest number on the table:\n";
std::cin >> min;
if (!std::cin) die();
std::cout << "Please enter the largest number on the table:\n";
std::cin >> max;
if (!std::cin) die();
if (min > max) die();
if (max - min >= MAX_SIZE) die();
if (choice == ADD) {
for (int i = 0; i <= max; i++) {
if (i == 0)
printf(" +");
else
printf("%3d", i);
printf(" ");
for (int j = min; j <= max; j++) {
printf("%3d ", i + j);
}
printf("\n");
}
}
if (choice == MULTIPLY) {
/* for printing header of the multiplication table */
std::cout << "X\t";
for (int j = min; j <= max; j++) {
std::cout << min * j << "\t";
}
std::cout << "\n";
/* for printing rest of the table */
for (int i = min; i <= max; i++) {
std::cout << i << "\t";
for (int j = min; j <= max; j++) {
std::cout << i * j << '\t';
}
std::cout << '\n';
}
}
}
The crucial mistake in your code for multiplication was that, you were trying to print (max - min + 1) + 1 rows in total, the extra +1 for the header. While your code was printing the first row as header and then starting directly with the second row.
Your code for addition table was correct, but 21 to 40 with tab character in between was too taking too much space for a typical laptop screen, not to say the output won't be pretty.
On my system, the output of tput lines and tput cols was 38 and 144 resp.
which wasn't sufficient for your code.
you can format the output with printf using printf fixed width output.
Considering you are not much familiar with C++, I would like to state that
using the std namespace as default namespace will work for this program, but when you working with larger projects, you should always prefix it.
I haven't enough reputation to add comment
if I were, I was commenting these lines
if (i == min) {
cout << 'X';
else
cout << i;
cout << '\t';
I have completed code that works for the majority of cases for outputting odd numbers between two integers in C++. However it doesn't work for negative numbers and/or if the two values are less than 3 in difference from one another (e.g. it works if the two numbers are 2 & 5, but does not work if the two numbers are 2 & 4).
I know that it is a cause of my code which adds 2 every time the while loop iterates, I'm just not sure how to rectify it.
while (secondOddNum - firstOddNum > 2)
{
if (firstOddNum % 2 > 0) //positive numbers
{
firstOddNum += 2;
sumOdd += pow(firstOddNum,2);
cout << firstOddNum << endl;
} else // even numbers
{
firstOddNum += 1;
sumOdd += pow(firstOddNum,2);
cout << firstOddNum << endl;
}
Thanks
I think your logic is overcomplicating the problem a little bit. Did you mean to do something like this?
void OutputOdds(int min, int max)
{
for(int i = min; i <= max; i++)
{
if(i % 2 == 1 || i % 2 == -1)
cout << i << " ";
}
}
Tests:
OutputOdds(-25, 6);
cout << endl << endl;
OutputOdds(1, 3);
cout << endl << endl;
OutputOdds(2, 4);
prints
-25 -23 -21 -19 -17 -15 -13 -11 -9 -7 -5 -3 -1 1 3 5
1 3
3
You can try something like this:
void printOddsBetween(int min, int max) {
int t = min + (min % 2 == 0);
while (t <= max) {
cout << t << endl;
t += 2;
}
}
It starts at the closest odd value to min. Then just prints every odd value up to max.
int min = 1;
int max = 11;
int counter = 0;
for (int i = min; i <= max; i++) {
if (i % 2 != 0) {
System.out.println(i);
counter += 1;
}
}
System.out.println("counter" + counter);
int xx[] = new int[counter];
int ii = 0;
for (int i = min; i <= max; i++) {
if (i % 2 != 0) {
xx[ii] = i;
ii += 1;
}
}
int firstNum{}, secondNum{};
cout << "Enter two numbers, the first smaller than the second."
<< endl;
cout << "Enter first integer: \t";
cin >> firstNum;
cout << endl;
while (firstNum < secondNum);
{
cout << "Enter second integer: \t";
cin >> secondNum;
cout << endl;
cout << "\nOdd numbers from " << firstNum << " to " << secondNum << " are \n";
for (int i = firstNum; i <= secondNum; i++)
{
if (i % 2 != 0)
{
cout << i << " ";
}
}
}
Prints: 2 & 19 ARE MY USER INPUTS
Enter two numbers, the first smaller than the second.
Enter first integer: 2
Enter second integer: 19
Odd numbers from 2 to 19 are
3 5 7 9 11 13 15 17 19
I have a file that contains a list of data something like this:
2012-01-01 Rain 7 13 0.28
2012-01-02 ScatteredClouds 4 8 0.25
2012-01-03 Rain 6 12 0.28
2012-01-04 Rain 5 10 0.28
2012-01-05 Rain 7 12 0.28
I have managed to design a class and extract the data into my program. I'm stuck now on designing:
how to find the sum of the 3rd column data
how to match the year to the other data.
eg: for case #2 - I want to find number of occurrences of 'Rain' in 2012.
P.S: I just started learning programming, sorry if the answer is obvious.
Here's my code:
const int SIZE = 2000;
class City
{
public:
string date;
string weatherDesc;
int minTemp;
int maxTemp;
double rainfall;
};
int main( )
{
City london[SIZE];
ifstream fin;
fin.open("weather.txt");
int i = 0;
while ((! fin.eof( )) && (i < SIZE))
{
fin >> london[i].date
>> london[i].weatherDesc
>> london[i].minTemp
>> london[i].maxTemp
>> london[i].rainfall;
cout << london[i].date << " "
<< london[i].weatherDesc << " "
<< london[i].minTemp << " "
<< london[i].maxTemp << " "
<< london[i].rainfall << endl;
i++;
}
}
You can simply examine each element in the array and see if each City meets the required conditions.
int weatherDescCount(City cities[], int count, string year, string desc)
{
int num = 0;
for (int i = 0; i < count; i++)
{
if (cities[i].weatherDesc == desc &&
cities[i].date.substr(0, 4) == year) {
num++;
}
}
return num;
}
int sumMinTemp(City cities[], int count)
{
int sum = 0;
for (int i = 0; i < count; i++)
{
sum += cities[i].minTemp;
}
return sum;
}
At the end of main(), add the following code:
cout << sumMinTemp(london, i) << endl;
cout << weatherDescCount(london, i, "2012", "Rain") << endl;
It prints 29 and 4 with your sample data, as expected.