How to print 3 different values per line in C++ - c++

My program reads 366 lines of data from a file, each line has 2 values; minimum temperature and maximum temperature. I want to output when there were three consecutive days where the temperature went above a certain number n, that the user enters.
This is what I have:
cout<<"Please enter a number to search: ";
cin>>n;
out<<endl;
out<<"Occasions during the year when there were three consecutive days
where the temperature went above "<<n<<" are:"<<endl;
out<<"Days: ";
for(int x=0; x<366; x=x+1){
in>>minimum[x];
in>>maximum[x];
if(minimum[x]>n){
day1=x;
}
if(maximum[x]>n){
day1=x;
}
out<<"Days: "<<day1<<", "<<day2<<", "<<day3<<endl;
}
}
I'm having trouble understanding how to update day 2 and day 3 to a different element of the array that satisfies the condition. When the condition is met, I want to store the days and print them like:
Occasions during the year (if any) when there were three consecutive days where the temperature went above 34 are:
Days:103, 104, 105
Days:107, 108, 109
Days:288, 289, 290
the days are the locations in the array.

Try something more like this:
cout << "Please enter a number to search: ";
cin >> n;
out << endl;
out << "Occasions during the year when there were three consecutive days where the temperature went above " << n << " are:" << endl;
int firstday, numdays = 0;
for (int x = 0; x < 366; ++x)
{
in >> minimum[x];
in >> maximum[x];
if (maximum[x] > n)
{
++numdays;
if (numdays == 1)
firstday = x;
else if (numdays == 3)
{
out << "Days: " << firstday << ", " << firstday+1 << ", " << firstday+2 << endl;
numdays = 0;
}
}
else
numdays = 0;
}
Alternatively:
cout << "Please enter a number to search: ";
cin >> n;
out << endl;
out << "Occasions during the year when there were three consecutive days where the temperature went above " << n << " are:" << endl;
for (int x = 0; x < 366; ++x)
{
in >> minimum[x];
in >> maximum[x];
}
for (int x = 0; x < 366-2; ++x)
{
if (maximum[x] > n)
{
int firstday = x;
int numdays = 1;
for (int y = 1; y < 3; ++y)
{
if (maximum[x+y] > n)
++numdays;
else
break;
}
if (numdays == 3)
out << "Days: " << firstday << ", " << firstday+1 << ", " << firstday+2 << endl;
x += (numdays-1);
}
}

I suggest you break this down into smaller parts. For example, you could do this in two broad steps:
Read in all the data
Find all sets of 3 days which are above the given temperature
By doing each of these separately, you can focus on one piece at a time, rather than trying to do both.
Note, that you only need if(maximum[x] > n).

Create an int variable to act as a flag. Every time you get a 'good' day, add 1 to that flag and subtract 1 if not. So, in the end, just add an if statement that checks if that flag variable is three, and then print the value.
Hope this helps!

Related

the code still print 0 and it can't calculate the required task

#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.

total the even numbers and product the odd

I am trying to make code that gets from user, the number of inputs and value of each input and then calculate total sum of the even numbers and product of the odd numbers.
I get to put in the first number but then the for loop does not work.
#include <iostream>
#include <vector>
int main() {
int totalNum;
int total_even;
int product_odd;
std::vector<int> numbers;
std::cout << "How many numbers would you like to entre?:";
std::cin >> totalNum;
std::cout << "\n";
for (int i = 1; i <= totalNum; i++){
std::cout << "Please entre number " << i << "\n";
std::cin >> numbers[i];
if (numbers[i] % 2 == 0) {
total_even = total_even + numbers[i];
} else {
product_odd = product_odd * numbers[i];
}
}
std::cout << "Sum of even: " << total_even << "\n";
std::cout << "Product of odd: " << product_odd;
}
First off, there's no need for a vector since, once you've finished with the number, you never need to use it again. Getting rid of the vector will remove the erroneous assignment to a non-existing element (appending to a vector is done with push_back rather than assigning beyond the end).
Second, since you're either adding the number to, or multiplying the number by, some accumulator, the accumulators should be initialised. You should initiliase total_even to zero and product_odd to one, so that the operations work out (0 + a + b == a + b, 1 * a * b == a * b). As it stands at the moment, your initial values are arbitrary so your results will also be arbitrary.
By way of example, here's a possible solution (though you should edit your own program rather than use this verbatim: it's a near-certainty that educators will be checking classwork, assuming that's what this is, for plagiarism):
#include <iostream>
int main() {
int numCount, thisNum, sumEven = 0, productOdd = 1;
std::cout << "How many numbers would you like to enter? ";
std::cin >> numCount;
std::cout << "\n";
for (int i = 1; i <= numCount; i++) {
std::cout << "Please enter number #" << i << ": ";
std::cin >> thisNum;
if (thisNum % 2 == 0) {
sumEven += thisNum;
} else {
productOdd *= thisNum;
}
}
std::cout << "\nSum of even: " << sumEven << "\n";
std::cout << "Product of odd: " << productOdd << "\n";
}
A sample run:
How many numbers would you like to enter? 6
Please enter number #1: 1
Please enter number #2: 2
Please enter number #3: 3
Please enter number #4: 4
Please enter number #5: 5
Please enter number #6: 6
Sum of even: 12
Product of odd: 15

Pick a number from two columns and calculate

A given file contains pairs of <two-digit number, amount>. Then take a toss-up two-digit number (called X), and compute the win/loss amount. The win/loss rule is if the input number matches X, then it’s a win and the winning total is (amount * 70); otherwise, it’s a loss of (-amount).
For example: [ticket.txt]
09 10
13 15
25 21
If the toss-up number is 09, the win/loss amount of the ticket is (10 * 70 - 15 - 21)
If the toss-up number is 42, the win/loss amount of the ticket is (-10 - 15 - 21).
This is my beginner project. I stuck at calculating the win amount and lost amount.
This is my problem
#include <iostream>
#include <fstream>
using namespace std;
int line1[100]; // array that can hold 100 numbers for 1st column
int line2[100]; // array that can hold 100 numbers for 2nd column
int main()
{
int winNum, winAmount, lostAmount;
int num = 0; // num start at 0
ifstream inFile;
inFile.open("Ticket.txt"); //open File
if (inFile.fail())
{
cout << "Fail to open the file" << endl;
return 1;
}
cout << "Numbers from File: " << endl;
while (!inFile.eof()) // read File to end of file
{
inFile >> line1[num]; // read first column, the first column is the number that user choosing
inFile >> line2[num]; // read second column, the second column is the amount of money that user paying
cout << "\n" << line1[num] << "\t" << line2[num];
++num;
}
inFile.close();
cout << endl;
cout << "Enter the toss-up number: "; // enter the win number
cin >> winNum;
if (line1[num] == winNum)
{
winAmount = line2[num] * 70; // number user choose = win number, winAmount = winAmount * 70 - lostAmount
cout << winAmount;
}
else
{
lostAmount =- line2[num]; //number user choose != win number, the amount will be -lost amounts
cout << lostAmount;
}
cout << endl << endl;
system("pause");
return 0;
}
You can see result at the end of the code
#include <iostream>
#include <fstream>
using namespace std;
int line1[100]; // array that can hold 100 numbers for 1st column
int line2[100]; // array that can hold 100 numbers for 2nd column
int main()
{
int winNum, winAmount = 0, lostAmount = 0, result = 0;
int num = 0; // num start at 0
ifstream inFile;
ifstream inFile2;
int rowNumber = 0;
string line;
inFile.open("Ticket.txt"); //open File
inFile2.open("Ticket.txt");
if (inFile.fail())
{
cout << "Fail to open the file" << endl;
return 1;
}
while (getline(inFile2, line))
++rowNumber;
cout << "Number of lines in text file: " << rowNumber << "\n";
int myArray[rowNumber][2];
for(int i = 0; i < rowNumber; i++)
for(int j = 0; j < 2; j++)
inFile >> myArray[i][j];
cout << "Numbers from File: " << endl;
for(int i = 0; i < rowNumber; i++)
{
for(int j = 0; j < 2; j++)
{
cout << myArray[i][j] << " ";
}
cout << "\n";
}
cout << endl;
cout << "Enter the toss-up number: "; // enter the win number
cin >> winNum;
for(int i = 0; i< rowNumber; i++)
{
if (myArray[i][0] == winNum)
{
winAmount = myArray[i][1] * 70; // number user choose = win number, winAmount = winAmount * 70 - lostAmount
}
else
{
lostAmount = lostAmount + myArray[i][1]; //number user choose != win number, the amount will be -lost amounts
}
}
result = winAmount - lostAmount;
cout << result;
cout << endl << endl;
system("pause");
return 0;
}
When you test line1[num] == winNum (and all the operations carried out after that) you're using the value of num that you modified with ++num;, this means you're working with empty or not meaningful values for both line1 and line2. For example, if the 3 rows of values showed in your "ticket.txt" are used, they are stored in postions 0, 1 and 2 of the arrays, while the num has a value of 4 at the end.
If I understood what you are trying to achieve, you should put the if-else statement in a for loop that goes from 0 to num, and then every operation on line1 and line2 should be done with the looping variable as an index.
Also, move the cout just after the loop if you want only total amounts to be displayed.

Exercise: for cycle and array

I have to write a program that allows to calculate the arithmetic average of an arbitrary numbers of values (chosen by the user)
It will outputs:
Number: 34
Number: 36
Number: 44
Number: //and I choose to stop input pressing
//Outputs:
It was inserted 3 numbers and the avarage is: 38
Of course i've forgot to post what i've done:
for (int x = 0; x < 50; x++){
cout << "Number: ";
cin >> number[x];
cout << "You have inserted the " << x << " element of the array;" << endl;
sum += number[x];
avarage = sum / number[x];
nEelementi = number[x];}
so I run the program, input some numbers, press something like ctrl+d or trying to add something to the code.. but it only goes from the first to the last element of the array with no values, becouse not entered, of course.. and then print absurd avarage and sum.
I know I don't need an array to do this but it's required from the exercise.. also the exercise only request to use for or while loop and arrays.
What I need is a way to stop the input and calculate the sum and avarage of only what I wrote.
edit1.
I've tried to dived by n writing for(x = 0; x < n, x++) because it made sense to me, but i think it "thinks" n, wrote like this, infinite, because the results is 0 (because the limit of a number divided by infinite is 0).. so i've started becoming mad.
Now i've started thinking that it would be easier to use while loop! and wrote
#include <iostream>
using namespace std;
int main() {
int num[50];
double sum = 0;
double average = 0;
int cont;
int end = 0;
while (cont < 50) {
cout << "num: ";
cin >> num[cont];
sum += num[cont];
cont++;
cout << "Want to continue 0 = sì, 1 = no";
cin >> end;
if (end == 1) {break;}
}
average = sum / cont;
cout << "You have insert " << cont << " elements" << endl;
cout << "LThe sum is: " << sum << endl;
cout << "The avarage is: " << average << endl;
return 0;
}
BUT still doesn't work. My professor says you should be able to stop input number by pressing ctrl+d so I'm not doing good.
Sorry for late answer but i have also to translate the code.. hope all translation is good:)
edit2.
#include <iostream>
int main() {
int sum = 0;
int num;
while ( std::cin ) {
std::cout << "Number: ";
std::cin >> num;
}
if ( std::cin >> num ) {
sum += num;
num++;
}
else {
std::cin.clear();
std::cout << "Input interrupted" << std::endl;
}
std::cout << "Sum is " << sum << std::endl;
std::cout << "You have entered " << num << " numbers" << std::endl;
return 0;
}
I love this new code, very simple and understandable to me, but I was not able to add sum operation, it only outputs 0! (leaving out average)
And also I was not able to determinate, and display, how many numbers I've entered. The last row of the code is just an example of what I want to do..
edit3.
Finally I made it.
#include <iostream>
using namespace std;
int main(){
double numero;
int index = 0;
double somma = 0.;
cout << "Inserire un numero: ";
while( cin )
{
if ( cin >> numero )
{
somma = somma + numero;
index++;
cout << "Inserire un numero: ";
}
else
{
cout << "Input interrotto" << endl;
}
}
cout << "Sono stati inseriti " << index << " numeri e la lora media è:
<< somma / index << endl;
return 0;
}
Thanks so much!
P.S. To the end, I don't need to use an array, it's just simple
There are a few problems here. One is that if the stream errors due to being closed or bad input, you don't recover and you just charge through your loop.
So first, make the loop terminate early if necessary. I'm also going to convert it to a while loop in preparation for the next part.
int x = 0;
while( std::cin && x < 50 )
{
std::cin >> number[x++];
}
Now it terminates early if the stream errors. But what if the user typed in "hello"? You could ignore it and continue like this:
if( std::cin >> number[x] )
{
x++;
}
else
{
std::cin.clear();
}
Notice that I didn't compute the sum or anything inside the loop. There's no need, since you are already putting them in an array. You can just do it after the loop. Here, I'm using std::accumulate
double sum = std::accumulate( number, number + x, 0.0 );
double average = 0.0;
if( x > 0 ) average = sum / x;
Now, you have also said you want an arbitrary number of values. Your original code allowed up to 50. Instead of storing them, you can instead just compute on the fly and discard the values.
double sum = 0.0;
int count = 0;
while( std::cin )
{
double value;
if( std::cin >> value )
{
sum += value;
count++;
}
else
{
std::cin.clear();
}
}
double average = 0.0;
if( count > 0 ) average = sum / count;
If you still want to store the values along the way, you can use a vector.
std::vector<double> numbers;
//...
numbers.push_back( value );
And if you want the user to choose the number of values:
std::cout << "Enter number of values: " << std::flush;
std::size_t max_count = 0;
std::cin >> max_count;
std::vector<double> numbers;
numbers.reserve( max_count );
while( std::cin && numbers.size() < max_count )
{
// ...
}

How can I get the array to show the previous list of array content before the next input?

I need the user input to be saved into my array and then output the array before the user inputs the next time. I have been moving things around different ways but cannot seem to get them to perform properly. I tried to cut down the code to the two functions I am having issues with.
void PlayGame()
{
const int HighestNum = 50;
const int LowestNum = 1;
int RandomNumber = LowestNum + rand() % HighestNum; //set for better random results
cout << "Guess the random number between " << LowestNum << " and " << HighestNum << "!\n\n";
const int attempts = 15;// limits the attempts to guess the random number to 15
int Guess [attempts] = {};
cout << "Enter your guess " << endl;
for (int count = 0; count < attempts; count++)
{
cin >> Guess[count];
int z = RandomNumber, y = Guess[count], r;
r = reviewGuess (z,y);//calling the function that determines the results
switch (r)//switch statement for function results, letting the user know if they matched the number, if the number is higher, or lower
{
case 0:
cout << "You Win!!" << endl;
cout << "\n";
cin.get();
return;
case 1:
cout << "The number is higher than your guess" << endl;
break;
case -1:
cout << "The number is lower than your guess" <<endl;
break;
}
if (count == 15)
{
cout << "Sorry, no guesses remain. The random number was... " << RandomNumber << "!";//so the user can see the random number at the end of their attempts
cout << "\n";
cin.get();
Again();
}
}
return;
}
int DisplayGuess(int member[])
{
for(int i = 0; i < 15; ++i)
cout << "\nGuess " << i + 1 << ": " << member[i];
cout << endl;
return;
}
Try this inside your loop
if(count > 0)
{
for (int j= 0; j < count; j++)
{
cout<<Guess[j];
}
}
Call DisplayGuess() in the first line of the for loop. Since the first you time you call it your array is empty, it shouldn't output anything.
So,
for (int count = 0; count < attempts; count++)
{
DisplayGuess(Guess[count]);
cin >> Guess[count];
int z = RandomNumber, y = Guess[count], r;
r = reviewGuess (z,y);//calling the function that determines the
results
. . . . . .