How can I see what is inside a vector? - c++

When I check the values inside of the homework vector using cout it seems to only be returning the value inside homework[0]. Can somebody look over my code and let me know where I'm going wrong?
int main()
{
cout << "Please enter midterm and final: " << endl;
double midterm, gfinal;
cin >> midterm >> gfinal;
cout << "Enter all your homework grades, " << endl;
double x;
cin >> x;
// initing a vector object named homework
vector<double> homework;
// show debug on the vector
while (homework.size() != 3)
homework.push_back(x);
if (homework.size() == 0)
{
cout << endl << "You need to enter at least one number";
return 1;
}
// vector before sorting
// since cout << homework did not seem to work I could always just write a debug function to iterate over structures and print them to the console
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
// sort the vector here
sort(homework.begin(), homework.end());
// vector after sorting
//cout << homework;
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
int mid = homework.size() / 2;
cout << "The below is mid" << endl;
cout << mid << endl;
double median;
if (homework.size() % 2 == 0)
median = (homework[mid - 1] + homework[mid]) / 2;
else
median = homework[mid];
//streamsize prec = cout.precision(3);
cout << "Your course grade is "
<< 0.2 * midterm + 0.4 * gfinal + 0.4 * median << endl;
//cout.precision(prec);
return 0;
}
This is the specific code that is causing me confusion:
// vector before sorting
// since cout << homework did not seem to work I could always just write a debug function to iterate over structures and print them to the console
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
// sort the vector here
sort(homework.begin(), homework.end());
// vector after sorting
//cout << homework;
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
When the program starts it asks for 2 values, so I plugged in 100 100.
Then it asks for 3 values so I used 80 90 100 the cout of all the homework positions is showing 80 when I am expecting 80 90 100.
The actual program works as the final cout returns 92 as expected.

In your code:
double x;
cin >> x; // <-- reading from cin only once
// initing a vector object named homework
vector<double> homework;
// show debug on the vector
while (homework.size() != 3)
homework.push_back(x); // <- inserting same value three times
you are reading from cin only once, i.e., you are reading a single value. Then, you are inserting that read value three times into the vector homework. Therefore, homework[0], homework[1] and homework[2] contain the same value.
Consider placing cin >> x inside the while loop to read three times from cin instead of just once, i.e., read from cin on each iteration of the loop:
vector<double> homework;
while (homework.size() < 3) {
double x;
cin >> x;
homework.push_back(x);
}

In addition to the bug that El Profesor pointed, for iterating a vector in modern C++, all you have to do is:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> homework{ 70,80,90 }; // For the example
// "See what is inside the vector":
for (auto grade : homework)
std::cout << grade << '\n';
}

So, the bugs have been fixed already. I will add a "more-C++"-style solution using STL algorithms.
For filling the vector, I will use std::copy_n. Meaning, read n values from std::cin and insert them into the target vector.
And for your question
How can I see what is inside a vector?
the solution is, iterate over the elements in the vector and copy the vectors values to ctd::cout. For this we will use the std::ostream_iterator
Please note: I always use qualifed names lke std::cout. Please consider. And I rarly use std::endl, becuase this always call flush, which is in most cases not needed. Also: All variables should always be initialized. Always.
And then, I added many comments. Please also consider. This improves the code readability and quality drastically.
Please see:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
constexpr size_t NumberOfHomeworkGrades = 3U;
int main()
{
// Print title and ask use to enter data
std::cout << "\nCalculation of course grade\n\nPlease enter midterm and final: " << '\n';
double midterm{ 0.0 };
double gfinal{ 0.0 };
std::cin >> midterm >> gfinal;
// Ask the use to enter the howmwork grades
std::cout << "Please Enter "<< NumberOfHomeworkGrades << " homework grades\n";
// Get the data from the user and put it into the vector
std::vector<double> homeworkGrades{};
std::copy_n(
std::istream_iterator<double>(std::cin), // We will iterate over std::cin and read data
NumberOfHomeworkGrades, // Over all we read data NumberOfHomeworkGrades times
std::back_inserter(homeworkGrades) // And we psuh the data into our homeworkGrades-vector
);
// Show the vector before sorting. Simply copy all data in the vector to std::cout using the ostream_iterator
std::cout << "\n\nEntered grades before sort\n";
std::copy(homeworkGrades.begin(), homeworkGrades.end(), std::ostream_iterator<double>(std::cout, "\n"));
// Sort the vector here
std::sort(homeworkGrades.begin(), homeworkGrades.end());
// Show the vector adter sorting. Simply copy all data in the vector to std::cout using the ostream_iterator
std::cout << "\n\nSorted grades\n";
std::copy(homeworkGrades.begin(), homeworkGrades.end(), std::ostream_iterator<double>(std::cout, "\n"));
// Calculate the median
double median{ 0 };
// First calculate the mid, to do the calculation only one time and to show the result
size_t mid{ homeworkGrades.size() / 2 };
if (!homeworkGrades.empty())
if (homeworkGrades.size() % 2 == 0)
median = (homeworkGrades[mid - 1] + homeworkGrades[mid]) / 2;
else
median = homeworkGrades[mid];
// Show the result to the user
std::cout << "\n\nThe mid value is (maybe truncated): " << mid
<< "\nThe median value is: " << median
<< "\n\nYour course grade is: " << 0.2 * midterm + 0.4 * gfinal + 0.4 * median << '\n';
return 0;
}

Related

adding digits in an array c++

I'm new to C++ and i was trying to understand how to work with arrays. The idea I have is:
I wanted a user to input an array, the program to output the
array
Double all the values in the array and output that
And for each of the doubled values, add the digits of the doubled number
(1 digit number would remain the same), then output the new numbers as
well.
(e.g. if the array was [5, 6, 7, 8], the doubled values would be [10, 12, 14, 16] and then you would add each values digits like, [1+0, 1+2, 1+4, 1+6] to get [1, 3, 5, 7].
I put my code to show my progress, feel free to point out any errors along the way!
Any help is appreciated!
p.s. The nested loop didn't work :(
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum-1;i++)
cout << num[i];
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum-1;j++)
{
num[j]*=2;
cout << num[j];
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
for (int k=0;k<maxNum;k++)
{
for (int l=0;l<maxNum;l++)
{
int sum[20];
while (num[k]!=0)
{
sum[l]=sum[l]+num[k]%10;
num[k]=num[k]/10;
}
}
cout << sum[l];
}
cout << endl;
}
A few things:
maxNum and num[] are never initialized, it's dangerous.
that is not how you scan input. Ideally you woud do smth like while(cin >> tem_var){}. Or you could modify it to be if( !(cin >> num[i]) ) break;. That way you don't need to do maxNum-1 later too. (cin>>) will be True if it reads a variable succesfully and False otherwise. That way you can stop scanning by entering any non-number string, instead of running the loop for the rest of iterations, but leaving num[i] uninitialized if that happens.
you forget to output delimeters between array numbers which makes it hard to read.
cout << num[i] << "|"; or smth.
In the last part you make 3 loops: a k for loop that you never use, a l for loop to iterate num, and a k while loop to sum the digits. One of them is not necessary.
In the last part sum[] array, though filled correctly, is not outputted. You declare it inside the l loop, meaning it's deleted when you exit it. And even if you declared it outside. your cout << sum[l]; is outside the l loop, meaning it will only try to do the cout << sum[maxNum]; (the value of l the loop finishes with) while you only have [0:(maxNum-1)] elements in num and sum filled.
I'd suggest you try smth like for(k=1;k<num[l];k*=10) sum[l]+= num[l] / k % 10; instead of that while loop. It's shorter, gets the job done and leaves num[l] unchaged in case you decide to use it again afterwards.
You need to initialize sum array with all zeros first. You don't need nested loop.
Create a sum array to store the sum of each number and initialize it with 0's. First write a loop to traverse through the elements of the doubled array. For each element write a loop(you chose while loop) to traverse through the digits of each number and them to the corresponding sum element.
I've modified your code a little bit, go through it once.
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum-1;i++)
cout << num[i]<<' ';
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum-1;j++)
{
num[j]*=2;
cout << num[j]<<' ';
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
int sum[20];
for (int i=0;i<maxNum-1;i++)
sum[i]=0;
for (int k=0;k<maxNum-1;k++)
{
// for (int l=0;l<maxNum;l++)
// {
while (num[k]!=0)
{
sum[k]=sum[k]+num[k]%10;
num[k]=num[k]/10;
}
cout << sum[k]<<' ';
// }
}
cout << endl;
}
You don't need nested loop for that ,while making logic behind any program take a simple example and get the result,Don't jump directly to code. This will help you to building logics.
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
int sum=0;
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum;i++)
cout << num[i]<<ends;
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum;j++)
{
num[j]*=2;
cout << num[j]<<ends;
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
int r=0;
for (int k=0;k<maxNum;k++)
{
while (num[k]>0)
{
r=num[k]%10;
sum+=r;
num[k]=num[k]/10;
}
cout<<sum<<ends;
sum=0;
r=0;
}
cout << endl;
}

Not able to figure out what is happening with the universal array

I have created a program which takes an equation. from the user by asking about the degree of the equation. and then taking the co-efficients from the user and then forming the function which results into an equation. and then I have used the bisection method to solve it.
The program is::
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
int stop=0,d,t[]={1};
float f(float x)
{
int loop,loopa;
float add=0.0,sum=0.0;
for(;stop==0;)
{
int p ;
cout << "Enter the degree of the poly. eq. (+ve integer)" << endl;
cin >> d ;
int *t = new int[d+1];
cout << "The eq. will be in the form of ax^"<<d<<"+bx^"<<(d-1)<<" and so on ." ;
p = 97 + d ;
for(loop=d;loop>=0;loop--)
{
cout << "Enter the value of " << char(p-loop) << endl;
cin >> t[loop];
cout << "a="<<t[loop]<<endl;
}
stop=1; //ARRAY IS STILL THERE WHY/////
} for(loop=0;loop<=d;loop++) cout<<"out="<<t[loop]<<endl;
//ARRAY IS GONE TILL NOW//
cout<<"d="<<d<<endl;
for(loopa=d;loopa>=0;loopa--)
{
cout<<"loopa="<<loopa<<"value="<<t[loopa]<<endl;
add = t[loopa] * pow(x,loopa);
sum=sum+add;
}
return sum;
}
int main()
{
float a , b , c , i , j ;
A:
cout << " Enter the starting point of interval " <<endl;
cin >> a ;
cout << " Enter the end point of interval " << endl;
cin >> b ;
cout << " Enter the number of iterations to be done . ( More the iterations , accurate is the result ) " << endl;
cin >> i ;
for(j=0;j<i;j++)
{
if(f(a)*f(b)>0)
{
cout << " The root of the above polynomial does not lies in the given interval . TRY AGAIN " << endl;
goto A;
}
else
{
c = a + b ;
c = c / 2 ;
if (f(a)*f(c)>0) a = c ;
else b = c ;
cout <<"hello"<< a << "aa \t" << b << "\t" << c << endl;
}
}
cout << "Root = "<< c <<endl;
}
When the user gives the value of degree it creates an array of size one more than degree is created then there is a for loop which takes the value of co-efficients in that array . The problem is the value of the array stays intact till the first for loop . but as the control proceeds to the second loop ( see the two comments ) the value of the array is gone...I am using CodeLite ...guys help me?????
To solve the array issue you just need to make a few small changes.
int stop=0,d,*t; // Declare an uninitialized pointer to int
float f(float x)
{
int loop,loopa;
float add=0.0,sum=0.0;
for(;stop==0;)
{
int p ;
cout << "Enter the degree of the poly. eq. (+ve integer)" << endl;
cin >> d ;
t = new int[d+1]; // Remove the int and asterix before t. You want to assign the new array to the pointer, not the value the pointer is pointing to.
cout << "The eq. will be in the form of ax^"<<d<<"+bx^"<<(d-1)<<" and so on ." ;
p = 97 + d ;
for(loop=d;loop>=0;loop--)
{
cout << "Enter the value of " << char(p-loop) << endl;
cin >> t[loop];
cout << "a="<<t[loop]<<endl;
}
stop=1; //ARRAY IS STILL THERE WHY/////
} for(loop=0;loop<=d;loop++) cout<<"out="<<t[loop]<<endl;
//ARRAY IS GONE TILL NOW//
cout<<"d="<<d<<endl;
for(loopa=d;loopa>=0;loopa--)
{
cout<<"loopa="<<loopa<<"value="<<t[loopa]<<endl;
add = t[loopa] * pow(x,loopa);
sum=sum+add;
}
delete[] t; // All new'ed things need to be deleted to not cause a leak. Delete it here since it is no longer needed.
return sum;
}
Please note that even if this works, it is not advised to use raw pointers in C++. Better to use an std::array<int> or std::vector<int> so you don't have to take care of the allocating and deleting of memory.
EDIT: Accidentaly left the int in fron of t. Changed now.

Keeping track of which is the smallest and which is the largest value so far in a loop

could you please help me with solving simple problem? I am very fresh with C++ and learning from book "Programming: Principles and Practice Using C++ by Bjarne Stroustrup". I have never learnt C++ before so I am not familiar with many useful features. The drill says:
"6. Now change the body of the loop so that it reads just one double
each time around. Define two variables to keep track of which is the
smallest and which is the largest value you have seen so far. Each
time through the loop write out the value entered. If it’s the
smallest so far, write the smallest so far after the number. If it is
the largest so far, write the largest so far after the number"
I do not know how to do this correctly without using vector. Here is my code:
#include "C:/std_lib_facilities.h"
int main()
{
double a, b,differ=0;
char c=' ';
cout << "Enter two values: \n";
while (c != '|' && cin >> a >> b )
{
if (a > b)
{
cout << "The smaller value is: "<< b << " and the larger value is: " << a << "\n \n";
differ = a - b;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else if (a < b)
{
cout << "The smaller value is: " << a << " and the larger value is: " << b << "\n \n";
differ = b - a;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else
{
cout << "These values are equal!\n";
}
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
And here are previous steps, these I have solved with code above:
Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the
program when a terminating '|' is entered.
Change the program to write out the smaller value is: followed by the smaller of the numbers and the larger value is: followed by the
larger value.
Augment the program so that it writes the line the numbers are equal (only) if they are equal.
Change the program so that it uses doubles instead of ints.
Change the program so that it writes out the numbers are almost equal after writing out which is the larger and the smaller if the two
numbers differ by less than 1.0/100.
Could you give me some hint how to do step 6.? I had some ideas but none of them worked..
Here is new code:
#include "C:/std_lib_facilities.h"
int main()
{
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
double a,differ=0;
char c=' ';
cout << "Enter value: \n";
while (c != '|' && cin >> a)
{
if (a > largestSoFar)
{
largestSoFar = a;
cout <<"Largest so far is: "<< largestSoFar << endl;
}
else if (a < smallestSoFar)
{
smallestSoFar = a;
cout <<"Smallest so far is: "<< smallestSoFar << endl;
}
else if(smallestSoFar >= a && a<=largestSoFar)
cout << a << endl;
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
I do not know how to do this correctly without using vector.
You do not need vector for this. The description correctly says that two variables would be sufficient:
// Declare these variables before the loop
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
Modify your loop to read into a, not into both a and b. Check the newly entered value against smallestSoFar and largestSoFar, do the printing, and re-assign smallest and largest as necessary. Note that the first time around you should see both printouts - for largest so far and for smallest so far.
Based on the knowledge that you are suppose to know at the current stage for the this assignment. The code should go something like this:
#include < iostream>
#include < cstdlib>
int main() {
double num_1 = 0;
double num_2 = 0;
double largest = 0;
double smallest = 0;
bool condition1 = true;
while (true) {
std::cin >> num_1;
if (num_1 > largest){
largest = num_1;
}
else if (num_1 < smallest) {
smallest = num_1;
}
std::cout << "The largest so far: " << largest << std::endl;
std::cin >> num_2;
if (condition1) {
smallest = largest;
condition1 = false;
}
if (num_2 < smallest) {
smallest = num_2;
}
else if (num_2 > largest) {
largest = num_2;
}
std::cout << "The smallest so far: " << smallest << std::endl;
}
system("pause");
return 0;
}
double large = 0;
double small = 0;
double input;
int counter = 0;
while (counter < 5) {
cin >> input;
cout <<"Large value: "<< large << '\t' <<"Small value: "<< small\
<< '\t' <<"Input value: "<< input << '\n';
if (input < small) {
cout << "The smallest value is " << input<<\
"\nthe largest value is "<< large<<'\n';
small = input;
}
else if (input > small&& input < large) {
cout << "The smallest value is " << small << \
"\nthe largest value is " << large<<'\n';
}
else if (input > small&& input > large) {
cout << "The smallest value is " << small << \
"\nthe largest value is " << input << '\n';
large = input;
}
counter += 1;

Determining if two numbers are "almost equal" and outputting the result

Please note that I am just starting C++.
I am working from Bjarne Stroustrup's book "Programming Principles and Practice Using C++ 2nd Edition" and am on a Drill at the end of chapter 4.
These are the instructions so far:
Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating '|' is entered.
Change the program to write out "the smaller value is:" followed by the smaller of the numbers and the "larger value is:" followed by the larger value.
Augment the program so that it writes the line "the numbers are equal" (only) if they are equal.
Change the program so that it uses doubles instead of ints.
5. Change the program so that it writes out "the numbers are almost equal" after writing out which is the larger and the smaller if the two numbers differ by less than 1.0/100.
This is where I am stuck.
First, I do not understand what "if the two numbers differ by less than 1.0/100." means. Does that mean if the two numbers are within 100 numbers of each other?
Second, how do I determine "if the two numbers differ by less than 1.0/100"? (The more simple the solution the better.)
Here is my code so far:
#include "std_lib_facilities.h"
int main()
{
double v1 = 0, v2 = 0;
cout << "Enter two numbers: ";
while(cin >> v1 >> v2)
{
if (v1 > v2)
cout << "The smaller of the two numbers is: " << v2 << "\n";
else if (v1 == v2)
cout << "The numbers are equal. \n";
else
cout << "The smaller of the two numbers is: " << v1 << "\n";
cout << "Enter two numbers: ";
}
}
Thank you for taking the time to read this.
This may be what it means
if(std::abs(v1-v2)<0.01)
#Walter 's answer may also be correct. It depends on the intention of the original question, which is not quite clear. For example, if #Walter 's version is used, then for v1 = v2 = 0.0, the program would say they are not close.
I think it means that the relative difference between the two floating point numbers is less than 1 part in 100, i.e.
if(std::abs(x-y)<0.01*std::max(std::abs(x),std::abs(y)))
Here I use the maximum of the absolute values as reference. You may also use the mean, but taking (the absolute of) either value is less advisable because it's not symmetric.
I have understood the assignment the following way:
#include "std_lib_facilities.h"
int main()
{
double v1 = 0, v2 = 0;
cout << "Enter two numbers: ";
while(cin >> v1 >> v2)
{
if ( v1 < v2 )
{
cout << "The smaller of the two numbers is the first number: " << v1 << "\n";
cout << "The largest of the two numbers is the second number: " << v2 << "\n";
}
else if ( v2 < v1 )
{
cout << "The smaller of the two numbers is the second number: " << v2 << "\n";
cout << "The largest of the two numbers is the first number: " << v1 << "\n";
}
if ( abs( v1 - v2) < 1.0 / 100 )
{
cout << "The numbers are almost equal. \n";
}
cout << "Enter two numbers: ";
}
}
This is a dead topic but I thought I should clarify this. The difference between 2 numbers is the result of the subtraction between the largest number and the smallest number. Therefore you need to declare 2 variables to keep track of which is the smallest and which is the largest in each of the if-else statements. Therefore the code should look like this.
#include "std_lib_facilities.h"
int main()
{
double v1 = 0, v2 = 0, larger, smaller;
cout << "Enter two numbers: ";
while(cin >> v1 >> v2)
{
if (v1 > v2)
{
cout << "The smaller of the two numbers is: " << v2 << "\n";
smaller = v2;
larger = v1;
}
else if (v1 == v2)
{
cout << "The numbers are equal. \n";
}
else if(v1 < v2)
{
cout << "The smaller of the two numbers is: " << v1 << "\n";
smaller = v1;
larger = v2;
}
if((larger-smaller)<1.0/100)
{
cout << "the numbers are almost equal" << endl;
}
cout << "Enter two numbers: ";
}
}
return 0;
This is my version:
#include "std_lib_facilities.h" // Custom header file for this book
int main() {
double a, b;
while (cin >> a >> b) {
if (a < b) {
cout << "The smaller value is: " << a << '\n'
<< "The larger value is: " << b << '\n';
if ((b - a) < (1.0 / 100))
cout << "The numbers are almost equal\n";
}
else if (a > b) {
cout << "The smaller value is: " << b << '\n'
<< "The larger value is: " << a << '\n';
if ((a - b) < (1.0 / 100))
cout << "The numbers are almost equal\n";
}
else {
cout << "The numbers are equal\n";
}
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main(){
double n1, n2;
double smaller, larger;
double differ=1.0/100;
string small ="The smallest number is: ";
string large ="The largest number is: ";
string equal ="\nBoth numbers are almost equal\n";
while(cin>>n1>>n2){
if (n1==n2){
cout<<"Both number are abslute equal!!!";
continue;
}
else if(n1>n2){
cout<<small<<n2<<" ";smaller=n2;larger=n1;}
else if (n1<n2) {
cout<<large<<n2<<" ";larger=n2;smaller=n1;}
if(larger-smaller<=differ)
cout<<equal;
}
return 0;
}
Even though it's an old thread I've come across it whilst working through the the same book. In case any more students do the same, here's what I've come up with using 1.0 / 100 as the literal 0.01:
#include "../../std_lib_facilities.h"
double lower(double int1, double int2) //function to calculate the smallest of two doubles
{
if (int1 > int2)
return int2;
else
return int1;
}
double upper(double int1, double int2) //function to calculate the largest of two doubles
{
if (int1 < int2)
return int2;
else
return int1;
}
int main()
{
double val1, val2;
while (cin >> val1 >> val2)
{
double smallest = lower(val1, val2);
double largest = upper(val1, val2);
if (val1 == val2)
{
cout << "The values are equal.\n";
}
else
{
cout << "The smaller value is: " << smallest << "\n";
cout << "The larger value is: " << largest << "\n";
if (abs(largest - smallest) < 1.0 / 100)
{
cout << "The numbers are almost equal.\n";
}
}
}
}
By this point in the book you too should have already covered functions and can utilise them here to keep your main function tidy.
"5. Change the program so that it writes out "the numbers are almost equal" after writing out which is the larger and the smaller if the two numbers differ by less than 1.0/100."
The reason why you do not understand what the author is asking is because the question is based on SPECIFICALLY pure basic mathematical speech (Was hard for me to understand "math" word questions too). It's one of those questions you can only understand if you understand the grammar of math, complete the book: "Practical Algebra: A Self-Teaching Guide" finish that book and then read c++ from Bjarne, it's going to be extremely difficult if you can't understand basic mathematical grammar specially for hardcore programming language c++.
"the number are almost equal"
It is a figure of speech, doesn't mean that there's a special C++ function or library for it.
"if the two numbers differ by less than 1.0/100."
Literally means the difference of two numbers are equal to 1.0/100 which is 0.01, which means for example if (9.99 - 10) = 0.01. But there's more to the question which makes it tricky, not only the Author is asking for the difference of 0.01 but the difference has to be less than 0.01. so basically you can write the formula such as:
double a; // use the built-in type keyword "double" since the values are in decimal.
double b;
if ((a - b) < 0.01)
{
//statement code goes here.
}
Also you deserve a cookie since you're reading a C++ book from it's creator.
This has been working for me.
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
double x=0;
double y=0;
while(cin >> x ,cin >> y)
if (x > y){
cout << "The larger value is " << x << " the smaller value is " << y << "\n";
if (x - y < (1.0/100)) {
cout << "the numbers are almost equal" << endl;
}
}
else if (x < y){
cout << "The larger value is " << y << " the smaller value is " << x << "\n";
if (y - x < (1.0/100)) {
cout << "the numbers are almost equal" << endl;
}
}
else if (x == y)
cout << "the numbers must be equal\n";
}

C++ Array parameters and const value

I do not get arrays, Im sure there are easier ways to make this program but I must do it the teacher's way and I am lost.
This is the assigment:
I do not get how I should go about these arrays. most confusing thing I seen by far.
What I would like is a guide or help on how i should program these arrays or how I should program arrays period. Not asking to do the rest for me, I already know how to do most of this, its just the arrays I like to know how to do.
This is my current program:
#include<iostream>
using namespace std;
void getPoints(int pPossible[], double pEarned[], int numItems, int limit);
int sumArray(double
void getpoints(int pPossible[], double pEarned[], int numItems, int limit)
{
int count;
while (limit == limit)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numbItems > limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
count=1;
for(count=1; count<numItems; count++)
cout << "Enter points then points possible for Item " << count << ": ";
cin << pEarned[count] << pPossible[count];
return 0;
}
C++ array indexes are zero-based, so you should use zero for the initial value in the for loop. Also, you're missing the braces for the for loop body; as it is, it will run the cout line numItem-1 times and the cin line just once.
Another thing: the operators in the for's cin line should be >>, not <<. You want input here, not output.
Finally, like #ebyrob said, make numItems a reference parameter (it would be clearer for the caller to use a pointer instead, but the assignment asked for a reference parameter).
void getpoints(int pPossible[], double pEarned[], int& numItems, int limit)
{
//Read number of items
while (true)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numItems >= limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
//Read earned and possible for each item
for(int count=0; count<numItems; count++)
{
cout << "Enter points then points possible for Item " << count << ": ";
cin >> pEarned[count] >> pPossible[count];
}
return 0;
}