My exercise is as follows: Given a list of N integers, find its mean (as a double), maximum value, minimum value, and range. Your program will first ask for N, the number of integers in the list, which the user will input. Then the user will input N more numbers.
Here is my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Input n: ";
cin >> n;
int first; //**LINE NUMBER 1**
cout << "No 1 is: ";
cin >> first;
int max = first;
int min = first;
for (int i=1; i<n;i++) //**LINE NUMBER 2**
{
int x;
cout << "No " << i+1 << " is: ";
cin >> x;
first = x; //**LINE NUMBER 3**
if (max < x)
{
max = x;
}
if (min > x)
{
min = x;
}
}
cout << "max is: " << max << endl;
cout << "min is: " << min << endl;
cout << "mean is: " << (double) (max+min)/2 << endl; //**LINE NUMBER 4**
cout << "range is: " << max - min << endl;
return 0;
}
However, the solution is a bit different:
For line number 1, it is int first=0; instead of int first;
For line number 2, it is for (int i=1; i<n;++i) instead of for (int i=1; i<n;i++)
For line number 3, it is first += x; instead of first = x;
For line number 4, it is cout << "mean is: " << (double) first/n<< endl; instead of cout << "mean is: " << (double) (max+min)/2 << endl;
I tried some examples but both codes produce exactly the same results. Why is that? Or am I wrong somewhere?
Well:
None of the lines are, per se, WRONG. More so, they are just preferably done another way. ie:
int first =0 just ensures that first == 0 to begin with. int first; can cause problems because it is assigned, initially to an arbitrary number (whatever happens to be at the memory address that the variable points to)
although ++i and i++ work the same way in for loops as an iterator, they have a very slight difference in other usages. read more about that here
first += x is essentially first = first + x which more clearly outlines the difference between your code and it. This also makes it very clear why int first = 0 is so important. If first was some random value, then the sum of all the numbers (which is what first is supposed to be) would be randomly assigned to start at a number, not always 0.
this last one is the only one where you are, in fact, wrong. the mean is defined as the sum of all your data divided by the number of data points (same as average) where as the median is described as the middle point of the data, or the number that describes the middle point between the max and min of your data. Where you are calculating what you think is the mean is actually the median. The intricacy of this is that sometimes, depending on your data, the mean = median. For example, if your data is 3,4,5 then both the mean and median is equal to 4
I hope this clarifies things for you :)
Related
Problem to solve:
given an array or sequence of numbers the goal is to find the Max number obtained by the multiplication of some 2 numbers in that sequence.
example of inputs and outputs
Input:
2
100000 90000
Correct output:
9000000000
Input:
3
1 2 3
Correct output:
6
My Solution: get the 2 Maximum numbers in the sequence given and multiply them
my code works unless with one solution
My code
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void print(std::vector<int> const& input)
{
for (int i = 0; i < input.size(); i++) {
std::cout << input.at(i) << ' ';
}
}
int main()
{
vector<int> seq;
int n;
// Read the nb of elements in vect
cout << "please enter the number of elements in sequence"<<endl;
cin >> n;
// Read the vector
cout << "please enter the elements of the sequence"<<endl;
for (int i = 0; i < n; i++)
{
int input;
cin >> input;
seq.push_back(input);
}
cout << "sequence you entered" << endl;
print(seq);
// Find the 1st max element
double FisrtMax=*max_element(seq.begin(), seq.end());
cout <<endl<< "First Maximum Element is" << endl<< FisrtMax;
// remove the found element
std::vector<int>::iterator PosF = find(seq.begin(), seq.end(), FisrtMax);
seq.erase(PosF);
cout <<endl<< "sequence After removing the 1st maximum element" << endl;
print(seq);
// Find the 2nd max element
double SecMax = *max_element(seq.begin(), seq.end());
cout <<endl<< "Second Maximum Element is" << endl << SecMax;
//multiply the 2 elements
int total = (FisrtMax * SecMax);
cout <<endl<<"The Product of the 2 elemnts is "<< total;
return 0;
}
The Input :
please enter the number of elements in sequence
2
please enter the elements of the sequence
1000000
90000
The Output :
please enter the number of elements in sequence
2
please enter the elements of the sequence
1000000
90000
sequence you entered
10000002105376900002105376
First Maximum Element is
1e+06
sequence After removing the 1st maximum element
900002105376
Second Maximum Element is
90000
The Product of the 2 elements is -2147483648
There are several mistakes in the code:
cout << ... << ' ' syntax tries to print three whitespace characters letters using a single-quote which accepts a single letter not multiple. Use " " instead.
The result produced can't be held by an integer, you need to define size_t (which expands into unsigned long long in most compilers).
Side Tips:
In this syntax:
for (int i = 0; i < input.size(); i++)
You're trying to compare an integer to size_t (returned by size() member function of vector class object). Rather than that, declare i with size_t.
In this syntax:
std::vector<int>::iterator PosF = find(seq.begin(), seq.end(), FisrtMax);
You don't need to define such long type std::vector<int>::iterator, use auto keyword here:
auto PosF = find(seq.begin(), seq.end(), FirstMax);
Code redefined:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void print(std::vector<size_t> const &input) {
for (size_t i = 0; i < input.size(); i++)
std::cout << input.at(i) << " ";
}
int main(void) {
vector<size_t> seq;
int n;
// Read the nb of elements in vect
cout << "please enter the number of elements in sequence" << endl;
cin >> n;
// Read the vector
cout << "please enter the elements of the sequence" << endl;
for (int i = 0; i < n; i++) {
int input;
cin >> input;
seq.push_back(input);
}
cout << "sequence you entered" << endl;
print(seq);
// Find the 1st max element
double FisrtMax = *max_element(seq.begin(), seq.end());
cout << endl
<< "First Maximum Element is" << endl
<< FisrtMax;
// remove the found element
auto PosF = find(seq.begin(), seq.end(), FisrtMax);
seq.erase(PosF);
cout << endl << "sequence After removing the 1st maximum element" << endl;
print(seq);
// Find the 2nd max element
double SecMax = *max_element(seq.begin(), seq.end());
cout << endl
<< "Second Maximum Element is" << endl
<< SecMax;
//multiply the 2 elements
size_t total = (FisrtMax * SecMax);
cout << endl
<< "The Product of the 2 elements is " << total;
return 0;
}
Its Inputs:
please enter the number of elements in sequence
2
please enter the elements of the sequence
1000000
90000
It outputs:
sequence you entered
1000000 90000
First Maximum Element is
1e+06
sequence After removing the 1st maximum element
90000
Second Maximum Element is
90000
The Product of the 2 elemnts is 90000000000
Edit: This program successfully works on OnlineGDB and the program was compiled with C++14 flag.
I came across a practice problem wherein I am given with an array and I want to remove certain elements from it so that the sum becomes less than a given value but also the sum should be near to the given value.
Let the value be 17 and the array given be [2, 5, 6 , 8] then I can remove element 2nd such that the new array becomes [2, 6, 8] and the obtained sum is 16. Assume array to be in increasing order.
My attempt:
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main(){
ll a,b;
cin>>a>>b;
vector<ll> v;
map<ll,vector<ll>> mp;
ll sum=0;
for(ll i=0;i<b;i++){
ll x;
cin>>x;
v.push_back(x);
mp[x].push_back(i);
sum+=x;
}
for(auto x:v) cout << x << " ";
cout << endl;
// cout << sum << endl;
if(sum<=a){
cout << b << endl;
for(ll i=0;i<b;i++){
cout << i << " ";
}
cout << endl;
}
else{
// sort(v.begin(),v.end());
vector<ll> ind;
cout << "sum:" << sum<< endl;
for(auto i=v.begin();i!=v.end();++i){
cout << "i val:" << (*i) << endl;
sum = sum - (*i);
ind.push_back(*mp[*i].begin());
mp[*i].erase(mp[*i].begin());
v.erase(i-1,i);
for(auto x:v) cout << x << " ";
cout << endl;
if(sum>a) continue;
else break;
}
cout << sum << endl;
}
}
First make sure it's ordered. In a loop, starting with the largest number in the array, subtract it from the sum. Compare to the target value, if sum still greater then remove and go back to start of loop, if not then store the absolute value (DIF) in a variable and restart the loop. Now your loop should look at the next largest number in the array and subtract from sum. Assuming we have a value for DIF, compare the absolute value of the current comparison to DIF. If DIF is closer then remove the previous number, exit the loop, and you are done. Otherwise you'll continue until you find the best result.
My problem is finding the minimum value out of user defined number of inputs. Everything so far works just fine, except that. Every time I try and rearrange some code or try a new method, I keep getting the same output on the screen:
Sum of numbers entered is: 145.4
Average of numbers entered is: 24.2333
The Highest number entered was: 45
The Lowest number entered was: 6.95283e-310
I get this every single time, regardless of what is entered, or what different suggestion I try:
The Lowest number entered was: 6.95283e-310
I am aware of the use and implementation of Arrays. However, the assignment I'm doing hasn't even covered arrays yet. That is some number of chapters later. Please don't suggest arrays...
I've looked here:
Finding Maximum and Minimum values in c++ by user input
Didn't work
http://www.cplusplus.com/forum/beginner/38799/
Didn't work
changing the values of max/min didn't work either
#include <iostream>
using namespace std;
int main()
{
double number, numberitems, sum = 0, average, max, min;
cout << "Enter number of items: \n";
cin >> numberitems;
//Make sure user can not enter negatives
if ( numberitems < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number > max) {
max = number;
}
//minimum value entered
if (number < min) {
min = number;
}
//Make sure user can not enter negatives
if ( number < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Sum of all the numbers
sum = sum + number;
//Average of all the numbers
average = sum / numberitems;
}
std::cout << endl;
std::cout << endl;
std::cout << "Sum of numbers entered is: " << sum << '\n';
std::cout << "Average of numbers entered is: " << average <<'\n';
std::cout << "The Highest number entered was: " << max <<'\n';
std::cout << "The Lowest number entered was: " << min <<'\n';
return 0;
}
Made a temporary fix :3
double min = 99999999999999999999999999999999999999999999999;
I'm very new to this.
Updated
After reading more comments I saw I was missing <cfloat>. Using #include <cfloat> NOW everyone's suggestions above work. However, <cfloat> was not covered in class, at all. So I'm not sure if that is usable here?
#include <iostream>
#include <cfloat>
using namespace std;
int main()
{
int numberitems;
double number, sum = 0, average;
double max = 0;
double min = DBL_MAX;
cout << "Enter number of items: \n";
cin >> numberitems;
//Make sure user can not enter negatives
if ( numberitems < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number >= max) {
max = number;
}
//minimum value entered
if (number <= min) {
min = number;
}
//Make sure user can not enter negatives
if ( number < 0 ) {
std::cout << "I said not to enter a negative number...'\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Sum of all the numbers
sum = sum + number;
//Average of all the numbers
average = sum / numberitems;
}
//Print the results
// some cosmetic...
std::cout << endl;
std::cout << endl;
std::cout << "\n=================REPORT====================\n";
std::cout << '\n';
std::cout << "\tYour Totals\tValues\n";
std::cout << "\t-----------\t------\n";
std::cout << "\t Sum: " << sum << '\n';
std::cout << "\t Average: " << average <<'\n';
std::cout << "\t Highest: " << max <<'\n';
std::cout << "\t Lowest: " << min <<'\n';
return 0;
}
Again, <cfloat> works fine, but I'm not sure if I'm allowed to use it. What other ways around this are there?
The question already got good answers - shortly: min and max are uninitialized.
However
Above is very specific.
Of course it helps in this specific case but I feel a broader advise that would work here and in many other cases is needed.
Add printouts
Adding debug printouts to your code ("debugging without a debugger") is always helpful in such cases.
For example adding the following in your example may help:
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number > max) {
// debug - (remove before submission)
std::cout << "number is the new max! number = " << number
<< ", max = " << max << std::endl;
// end of debug
max = number;
}
//minimum value entered
if (number < min) {
// (debug - remove before submission)
std::cout << "number is the new min! number = " << number
<< ", min = " << min << std::endl;
// end of debug
min = number;
}
When calculating minimum and maximum, you should initialize your variables to a default value. For minimum, it's the maximal possible value; for maximum - the minimal possible one.
double max, min; // BUG - not initialized
#include <float.h> // or <cfloat>
...
double max = 0; // CORRECT - initialized
double min = DBL_MAX; // CORRECT - initialized
For maximum, the initialization is usually -DBL_MAX (note: not DBL_MIN), but 0 is good enough in this case, when no negative values exist.
You need to set an initial value for min and max. For min, I'd suggest using an initial value of DBL_MAX, which is defined in the header cfloat.
i am confused about how does this code flows especially after inputtedin the set of integers.
for example how will the input be stored and then compared to find the largest among the set?
#include <iostream>
using namespace std;
int main()
{
int n, num, max, k=1;
cout << " Enter how many integers " << endl;
cin >> n;
cout << " enter " << n << " integers: "; // where input be stored
cin >> max; // this will input the last number right?
// if i entered 50 55 60 where they will be stored dont i need to store them in in 3 seprate places
while (k<n)
{
cin >> num; // what is the function of this line? from where the input will be
if (num > max)
max = num;
k++;
}
cout << " largest integer is :" << max << endl;
return 0;
}
Let's walk through this.
Let's consider the case the user selects n >= 1. (note also k = 1).
We first need the user to enter one number.
cin >> max;
We say that this number is the max, we don't know if it's true or not but we make this assumption.
We then read in integers while k < n is true.
while (k < n)
{
cin >> num;
if (num > max)
max = num;
k++;
}
So, we read a number into num (which we declared outside the while loop).
We then check if this number is greater than our assumption that the first number was the biggest, if it is we reassign max to be equal to num.
We then increment k.
We do this until we have read in n integers.
Resulting in max being the largest number we entered.
As for storage, we're not needing to store anything, inside the scope of the while loop we can do the check if the number is larger than max or not, if it wasn't we just discard it with the next iteration.
It doesn't store the entire set of numbers read.
It compares each new one entered to the current maximum. The initial maximum value is set to the first number read.
Problem statement of this program will be like : You are given n integers. Now you have to print the largest integer among all these integers.
cin >> max will take only one integer as input. max will hold the value.
cout << " enter " << n << " integers: "; will print this output in the console. For example, if value of n is 2, then this will print: enter 2 integers:
Look in the comment for further details:
#include <iostream>
using namespace std;
int main() {
int n, num, max, k = 1;
cout << " Enter how many integers " << endl; // print
cin >> n; // number of integer to input;
cout << " enter " << n << " integers: "; // print how many integers to enter as input
cin >> max; // input for 1st integer, assume it is the maximum integer
// this while loop will take input of the remaining n-1 intergers
// initially k=1, while loop will run until k is less than n
// while loop will run for n-1 times
while (k < n) {
cin >> num; // input for 1 integer
if (num > max) max = num; // if this input integer 'num' is greater than 'max', then update 'max'
k++; // increment 'k'
}
cout << " largest integer is :" << max << endl; // print the largest integer
return 0;
}
I bought the textbook C++ How to program 9th edition and I have come across a question that I am just stumped on, even though it is probably pretty simple. The question all summed up is this: "Use a while statement to determine and print the largest number of 10 numbers entered by the user". But here is the part that stumps me. The question wants me to use only 3 variables. counter, number, and largest. I know to make counter variable go up by 1 for each number entered until it gets to 10, and I know the number variable is used for input. I just can't seem to find out how to use the largest variable, or how to check to see what value is the largest without using other variables. This is all I have so far. Right now I put a break in the code so it wouldn't be an infinite loop.
UPDATED CODE
#include <iostream>
using namespace std;
void main()
{
int counter = 0;
int number = 0;
int largest = 0;
cout << "Please enter up to 10 numbers and I will print the largest one on the screen.\n\n";
while (counter <= 10)
{
cout << "Number: ";
cin >> number;
counter++;
if (number > largest)
{
largest = number;
}
else if (counter == 10)
{
cout << "The largest number was: " << number;
break;
}
}
}
cout << "The largest number was: " << number;
should be
cout << "The largest number was: " << largest;
Inside the while loop, if number is greater than largest, then set largest = number.
Then at the end you can output largest.
Solution(you don't even need a while loop)
#define MAX_NUM 8
//user input goes in myints
int myints[MAX_NUM] = {3,7,2,5,6,4,9};
// using default comparison:
std::cout << "The largest element is " << *std::max_element(myints,myints+MAX_NUM) << '\n';
Other Solution using int arrays even though you can replace int array with one variable
int main()
{
int largest = 0;
int myints[10] = {3,7,2,5,6,4,9,7,2,6};
for(int i =0 ; i< 10;i++)
{
if (myints[i] > largest)
{
largest = myints[i];
}
}
cout << largest << endl;
return 0;
}
Compiled Code
Second Compiled Code
You just need to add in while loop checking is the number you entered bigger than largest. If it is you just store it in largest. And actually you are entering 11 numbers because you count from 0 to 10. Just set counter to 1 or while(counter < 10)
int counter = 1;
int number = 0;
int largest = 0;
cout << "Please enter up to 10 numbers and I will print the largest one on the screen.\n\n";
while (counter <= 10)
{
cout << "Number: ";
cin >> number;
counter++;
if (largest < number)
{
largest = number;
}
}
cout << largest << endl;