0
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;

const string ID = "- CS 1361, Spring 2008 - Lab 39";
void PrintDblArray (double[],int,ofstream&);
int Smallest(double[],int);


int main()
{
	int i;
	double n,
		arr[50];

  ifstream fin;
  ofstream fout;
  cout << "Running Lab 35 . . . " << endl << endl;
  fout.open("- CS 1361, Spring 2008 - Lab 39.out");
  fin.open("lab39.dat");

	if (!fin)
	{                                             
	cout << "Can't open the input file." << endl << endl;
	return 1;
	}
	//Teh Output
	fout << ID << endl << endl;

	for (i = 0; fin >> n; i++)
		arr[i] = n;

	fout << fixed << showpoint << setprecision(1);
	fout << setw(14) << "Smallest:  ";

	fout << Smallest(arr,i) << endl << endl;
	fout << "Numbers:" << endl;
	PrintDblArray (arr,i,fout);

	
	return 0;

}
	void PrintDblArray(double arr[],int i,ofstream& fout)
	{
		int j;
		for (j = 0; j < i; j++)
		fout << setw(2) << j+1 << setw(10) << arr[j] << endl;
	}

	int Smallest (double arr[],int i)
	{
		double x;
		int y;

		for (y = 0, x = 0; y <= i; y++)
		{
			if (arr[y] < x)
				x = arr[y];
			else if (arr[y] > x)
				x = arr[y];
		}
		return x;
	}

My function int Smallest, is supposed to print the smallest number in the array. Its prints some random number such as,"-2147483648." which is wrong. I need it to print a smaller number such as -3500.0 Please tell me what I am doing wrong and an explanation would be nice.

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by Ancient Dragon
0

>>for (y = 0, x = 0; y <= i; y++)

should be < operator, not <= because array values range from 0 to, but not including, i

Also, initialize arrays with 0 when declared to insure they do not contain random data arr[50] = {0}; In that same function x should be initialized to arr[0], not 0. for (y = 1, x = arr[0]; y < i; y++) >>else if (arr[y] > x)
>> x = arr[y];

Delete those two lines -- that function is supposed to find the smallest number, not the largest.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.