Page 3 of 3

Re: push_back, square( )ect.ect.

Posted: Sat Apr 04, 2009 8:59 pm
by cplusplusnoob
i didnt include the stuff before that generally so not to bore you but i will now make it clear.

Code: Select all

#include"stdafx.h"
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
	vector<double>temps;
	double temp;
	while((cin>>temp) && (temps.size() <2))
		 temps.push_back(temp);
	double sum=0;
	for (unsigned int i=0;i<temps.size();++i)sum+= temps[i];
	cout<<"average temurature: "<<sum/temps.size()<<endl;
	sort(temps.begin(),temps.end());
	cout<<"medean temurature: "<<temps[temps.size()/2]<<endl;
	if(temps[0]<temps[1] && temps[2])
		cout<<temps[0]<<" is the least.\n";
	else if (temps[1]<temps[0] && temps[2])
		cout<<temps[1]<<" is the least.\n";
	else 
		cout<<temps[2]<<" is the least.\n";
cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
it prints the medean line but the if statements must be interupted by the warning.

Re: push_back, square( )ect.ect.

Posted: Sat Apr 04, 2009 10:40 pm
by kostiak2
Were you trying to do:

Code: Select all

if(temps[0]<temps[1] && temps[0]<temps[2])
which will compare temps[0] to temps[1] and temps[2]?

Either way, you should not do the if statements at all, as you already sorted the array, which means that temps[0] will always the lowest after the sort that you did.

Now, you really need to learn about naming variables and proper spacing:

Code: Select all

#include"stdafx.h"
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
    vector<double> tempArray;
    double temp;
    double sum=0;

    while((cin>>temp) && (tempArray.size() <2))
    {
       tempArray.push_back(temp);
    }

    for (unsigned int i=0;i<tempArray.size();++i)
    {
        sum+= temps[i];
    }
    cout << "average temurature: " << sum/tempArray.size() << endl;

    sort(tempArray.begin(), tempArray.end());
    cout << "medean temurature: " << tempArray[tempArray.size()/2] << endl;

    cout << tempArray[0] << " is the least.\n";
    cin.clear();
    cin.ignore(255, '\n');
    cin.get();

    return 0;
}
That makes your code just a bit more readable.

Re: push_back, square( )ect.ect.

Posted: Sun Apr 05, 2009 1:20 am
by Maevik
How many data are you trying to take as input? Currently you prompt the user 3 times, but only store the first two values into your vector.

Your first while loop should look something more like

Code: Select all

    while( tempArray.size() < x )
    {
		cin >> temp;
        tempArray.push_back(temp);
    }
where x is the number of values you want to get from the user.