So I am making a program that calls functions to generate random numbers. Then calls a function to print those results. The second thing I want to print is the random numbers but after they are sorted in ascending order. After some tweaking with the ascending order function for an array, I try displaying it with my print function and nothing happens
Originally it did display as a second part of the output, but it didn't work and only showed 0's. Now I think I fixed the code but now it won't even display anything in the output so I have no way to check if its working and I am really confused as to why
#include <iomanip>
#include <iostream>
#include <cstdlib>
using namespace std;
#define lowerbound 10.0
#define upperbound 950.0
#define min_values 75
#define max_values 150
#define max_val_file 40
#define max_output 12
double randDouble();
int buildRandom(double array[]);
void print(string, double array[], int);
void sort(double array[], int);
int main()
{
srand(19);
int num_vals;
double random_array[max_values];
double sorted_array[max_values];
string title1 = "Random Values";
string title2 = "Sorted Random Values";
num_vals = buildRandom(random_array);
cout << "There are " << num_vals << " values in the first array" << '\n';
print(title1, random_array, num_vals);
sort(random_array, num_vals);
cout << '\n';
print(title2, sorted_array, num_vals);
}
double randDouble()
{
int random_integer = rand();
double random_value;
random_value = lowerbound + (random_integer / (RAND_MAX / (upperbound - lowerbound)));
return random_value;
}
int buildRandom(double random_array[])
{
int num_vals = min_values + rand() % (max_values - min_values + 1);
int i;
double random_num;
for (i = 0; i < num_vals; ++i)
{
random_num = randDouble();
random_array[i] = random_num;
}
return num_vals;
}
void print(string title, double random_array[], int num_vals)
{
int i;
cout << '\n' << title << '\n' << '\n'<< setw(8);
for (i = 0; i < num_vals; ++i)
{
cout << setprecision(3) << fixed << random_array[i] << setw(9);
if ((i + 1) % max_output == 0)
{
cout << '\n' << setw(8);
}
}
}
void sort (double sorted_array[], int numberOfValues)
{
int top = 0;
int x, SSF, PTR;
double swap;
double last = numberOfValues - 1;
for (top = 0; top < last; ++top)
{
PTR = top;
SSF = top;
for (x = 0; PTR < last; ++x)
{
if (sorted_array[PTR] < sorted_array[SSF])
{
SSF = PTR;
}
}
swap = sorted_array[SSF];
sorted_array[SSF] = sorted_array[top];
sorted_array[top] = swap;
}
}
Related
For class I had to write a program that calculated 12 different "grades". I used 2 different arrays - "numerator[ ]" and "denominator[ ]" which each have a size of 12 (12 different ints). For this assignment, I had to make the value of 3 of the denominators 0, which indicated that the corresponding numerator to those denominators equaled "bonus points" (example- grade 5/0 would equal 5 bonus points). However, now I have to create a "data cleanup" function, which takes all the scores with non-zero denominators, and move them into a new empty array (leaving me with only "real" scores, which I made as newNumerator[ ], and newDenominator[ ], as well as the new size of each array "newSize". The data cleanup function needs to have these parameters-
dataClean(int numerator[], int denominator[], int size, int newNumerator[], int newDenominator[], int &newSize)
I need to populate the new arrays and define newSize of those arrays within the cleanData function, and to have their new values come back to main() through the parameters. However, I have been stuck on this part for quite some time. I am not sure if I need to use pointers or not, and even so I am very unclear on how to use them. Sorry if this is unclear, this assignment has been very confusing to me. Any help is appreciated. Please let me know if you need any further clarification for anything.
data file of numerators and denominators (data.txt)
72 49 23 5 9 10 6 16 26 54 4 55//numerator[]
75 50 25 0 10 0 0 20 30 55 5 60//denominator[]
program-
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
typedef int arrayType[];
void readData(int numerator[], int denominator[], int size);
void reportData(arrayType, arrayType, int);
void reportOverall(int numerator[], int denominator[], int size);
void cleanData(int numerator[], int denominator[], int size, int newNumerator[], int newDenominator[], int &newSize);
int main()
{
const int size = 12;
int numerator[size];
int denominator[size];
int newSize = 12;
int newNumerator[newSize];
int newDenominator[newSize];
cout << fixed << showpoint << setprecision(1);
readData(numerator, denominator, size);
reportData(numerator, denominator, size);
reportOverall(numerator, denominator, size);
cout << "\n******************************\n";
cleanData(numerator, denominator, size, newNumerator, newDenominator, &newSize);
reportData(newNumerator, newDenominator, newSize);
system("pause");
return 0;
}
void readData(int numerator[], int denominator[], int size)
{
ifstream dataIn;
dataIn.open("data.txt");
if(!dataIn)
{
cout << "File not found\n";
system("pause");
exit(1);
}
int count;
for(count = 0; count < size; count++)
{
dataIn >> numerator[count];
}
for (count = 0; count < size; count++)
{
dataIn >> denominator[count];
}
dataIn.close();
}
void reportData(arrayType numerator, arrayType denominator, int size)
{
int count;
for (count = 0; count < size; count++)
{
if (denominator[count] == 0)
{
cout << "Score " << (count + 1) << " is " << numerator[count] << "/" << denominator[count] << " = " << "Bonus points!\n";
}
else
{
double percent = 100.0 * static_cast<double>(numerator[count]) / denominator[count];
cout << "Score " << (count + 1) << " is " << numerator[count] << "/" << denominator[count] << " = " << (percent) << "%\n";
}
}
}
void reportOverall(int numerator[], int denominator[], int size)
{
int count;
int totalNumerator = 0.0;
int totalDenominator = 0.0;
for (count = 0; count < size; count++)
{
totalNumerator += numerator[count];
}
for (count = 0; count < size; count++)
{
totalDenominator += denominator[count];
}
double overallPercent = 100.0 * static_cast<double>(totalNumerator) / (totalDenominator);
cout << "Total Points Earned (numerators): " << totalNumerator << endl;
cout << "Total Points Possible (denominators): " << totalDenominator << endl;
cout << "Overall Grade: " << overallPercent << "%\n";
}
void cleanData(int numerator[], int denominator[], int size, int *newNumerator[], int *newDenominator[], int &newSize)
{
int count;
for(count = 0; count < size; count++)
{
int count2 = 0;
if(denominator[count] != 0)
{
*newNumerator[count2] = numerator[count];
*newDenominator[count2] = denominator[count];
newSize--;
count2++;
}
}
}
you need to fix the function call and cleanData defintion with proper referencing of parameters
within main:
cleanData(numerator, denominator, size, newNumerator, newDenominator, newSize);
void cleanData(int* numerator, int* denominator, const int size, int *newNumerator, int *newDenominator, int newSize)
{
int count;
for(count = 0; count < size; count++)
{
int count2 = 0;
if(denominator[count] != 0)
{
newNumerator[count2] = numerator[count];
newDenominator[count2] = denominator[count];
newSize--;
count2++;
}
}
}
This question already has answers here:
C++ Sorting the "percentage" of two paired integer arrays
(3 answers)
Closed 7 years ago.
I have a program with 2 "paired" integer arrays newNumerator[ ], and newDenominator[ ] which both have 9 integers in them. I wrote a function that sorts them in ascending order (lowest percentage or 'ratio' to highest), however it outputs the elements in the same order as they were before, and doesnt sort it at all. Here is the code, and sortData is the function that is (supposed) to sort it.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
typedef int arrayType[];
void readData(int numerator[], int denominator[], int size);
void reportData(arrayType, arrayType, int);
void reportOverall(int numerator[], int denominator[], int size);
void cleanData(int* numerator, int* denominator, const int size, int *newNumerator, int *newDenominator, int &newSize);
void reportMin(int newNumerator[], int newDenominator[], int newSize);
void sortData(int newNumerator[], int newDenominator[], int newSize);
void hrule();
int main()
{
const int size = 12;
int numerator[size];
int denominator[size];
int newSize = 12;
int newNumerator[newSize];
int newDenominator[newSize];
cout << fixed << showpoint << setprecision(1);
readData(numerator, denominator, size);
reportData(numerator, denominator, size);
reportOverall(numerator, denominator, size);
hrule();
cleanData(numerator, denominator, size, newNumerator, newDenominator, newSize);
cout << "There are " << newSize << " scores that are not bonuses:\n";
reportData(newNumerator, newDenominator, newSize);
reportMin(newNumerator, newDenominator, newSize);
hrule();
sortData(newNumerator, newDenominator, newSize);
cout << "The scores from highest to lowest are: " << endl;
reportData(newNumerator, newDenominator, newSize);
system("pause");
return 0;
}
void readData(int numerator[], int denominator[], int size)
{
ifstream dataIn;
dataIn.open("data.txt");
if(!dataIn)
{
cout << "File not found\n";
system("pause");
exit(1);
}
int count;
for(count = 0; count < size; count++)
{
dataIn >> numerator[count];
}
for (count = 0; count < size; count++)
{
dataIn >> denominator[count];
}
dataIn.close();
}
void reportData(arrayType numerator, arrayType denominator, int size)
{
int count;
for (count = 0; count < size; count++)
{
if (denominator[count] == 0)
{
cout << "Score " << (count + 1) << " is " << numerator[count] << "/" << denominator[count] << " = " << "Bonus points!\n";
}
else
{
double percent = 100.0 * static_cast<double>(numerator[count]) / denominator[count];
cout << "Score " << (count + 1) << " is " << numerator[count] << "/" << denominator[count] << " = " << (percent) << "%\n";
}
}
}
void reportOverall(int numerator[], int denominator[], int size)
{
int count;
int totalNumerator = 0.0;
int totalDenominator = 0.0;
for (count = 0; count < size; count++)
{
totalNumerator += numerator[count];
}
for (count = 0; count < size; count++)
{
totalDenominator += denominator[count];
}
double overallPercent = 100.0 * static_cast<double>(totalNumerator) / (totalDenominator);
cout << "Total Points Earned (numerators): " << totalNumerator << endl;
cout << "Total Points Possible (denominators): " << totalDenominator << endl;
cout << "Overall Grade: " << overallPercent << "%\n";
}
void cleanData(int* numerator, int* denominator, const int size, int *newNumerator, int *newDenominator, int &newSize)
{
int count;
int count2 = 0;
for(count = 0; count < size; count++)
{
if(denominator[count] != 0)
{
newNumerator[count2] = numerator[count];
newDenominator[count2] = denominator[count];
count2++;
}
else if(denominator[count] == 0)
{
newSize--;
}
}
}
void reportMin(int newNumerator[], int newDenominator[], int newSize)
{
double minimum;
int count;
int location = 0;
double quotient;
for(count = 0; count < newSize; count++)
{
quotient = 100.0 * static_cast<double>(newNumerator[count]) / newDenominator[count];
if (count == 0 || quotient < minimum)
{
minimum = quotient;
location = count;
}
}
cout << "The lowest earned percentage grade is " << newNumerator[location] << "/" << newDenominator[location] << " = " << minimum << "%\n";
}
void sortData(int newNumerator[], int newDenominator[], int newSize)
{
int temp1;
int temp2;
bool swap;
int count = 0;
double percentageLeft = 100.0 * static_cast<double>(newNumerator[count]) / newDenominator[count];
double percentageRight = 100.0 * static_cast<double>(newNumerator[count + 1]) / newDenominator[count + 1];
do
{ swap = false;
for(count = 0; count < (newSize - 1); count++)
{
if(percentageLeft > percentageRight)
{
temp1 = newNumerator[count];
newNumerator[count] = newNumerator[count + 1];
newNumerator[count + 1] = temp1;
temp2 = newDenominator[count];
newDenominator[count] = newDenominator[count + 1];
newDenominator[count + 1] = temp2;
swap = true;
}
}
} while (swap);
}
void hrule()
{
cout << "\n****************************************\n\n";
}
Data file-
72 49 23 5 9 10 6 16 26 54 14 55
75 50 25 0 10 0 0 20 30 55 15 60
You're computing your percentageLeft and percentageRight outside your loop. Those values never change as you are swapping things.
You probably want them as the first line inside your for loop.
Because the first two don't need to be swapped, it thinks none of the elements ever need to be swapped. If the first two DID need to be swapped, your program would run forever, as the if statement if(percentageLeft > percentageRight) would always be true and swap would always be set to true leading to an infinite loop.
I'm new, don't know what I'm doing.
The compile warnings are on and do not show any warnings. Executable pops up and alerts of Run Time Check Failure #2.
Help would be appreciated as to why this is happening.
#include <iostream>
#include <string>
using namespace std;
class romanType {
public:
string strg;
void inputRoman(int ary[]);
//void CalculateRoman(int ary[]);
//void outputRoman(int total);
};
int main()
{
int M = 1000;
int D = 500;
int C = 100;
int L = 50;
int X = 10;
int V = 5;
int I = 1;
romanType numerals;
int ary[50];
cout << "This is to convert your input of Roman numerals to a positiver integer" << endl;
cout << "When prompted, do as you're told" << endl;
numerals.inputRoman(&ary[50]);
// numerals.CalculateRoman(&input[50]);
return 0;
}
void romanType::inputRoman(int ary[])
{
string strg;
int array_size;
int i;
cout << "Input the an appropriate Roman Numeral value" << endl;
cin >> strg;
array_size = strg.length();
for (i = 0; i < array_size; i++)
{
ary[i] = strg[i];
}
}
/*
void romanType::CalculateRoman(int ary[])
{
int total = 0;
int i;
for (i=0; i < 50 ; i++){
if (ary[i] < (ary[i + 1])){
total = total + (ary[i + 1] - ary[i]);
}
else {
total = total + ary[i];
}
}
cout << "Your conversion should equal " << total << endl;
}
*/`
&ary[50] is the address of 51st element of ary, which means it points just after the last element of ary. Change it to ary:
numerals.inputRoman(ary);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I was writing code for a school assignment which is supposed to ask the user for a limit and call a function that would generate the values of a given series to an array and pass it back to the call method to get printed. Here's my code so far:
Header:
/*
* series.h
*/
#ifndef SERIES_H_
#define SERIES_H_
// Direct calls for testing - DELETE AFTER
double log(int x);
double exp(int x);
double fib(int x);
double fac(int x);
// Global
enum SERIES {LOG, EXP, FIB, FAC};
void getSeries(SERIES _s, double _limit, int& _length, double *series);
double mean(double* _values, int length);
void printSeries(double* _series, int _length);
#endif /* SERIES_H_ */
CPP:
/*
* series.cpp
*/
#include "series.h"
#include <cmath>
#include <iostream>
using namespace std;
int factorial(int x) {
return (x == 1 ? x : x * factorial(x - 1));
}
double log(int x) {
return ((double)x - ((double)(pow(x,2)) / (double)(2))
+ ((double)(pow(x,3)) / (double)(3)));
}
double exp(int x) {
return (((double) 1) + ((double) x)
+ ((pow((double) x, 2)) / ((double) factorial(2)))
+ ((pow((double) x, 3)) / ((double) factorial(3)))
+ ((pow((double) x, 4)) / ((double) factorial(4))));
}
double fib(int x) {
return (x < 2 ? x : (fib(x - 1) + fib(x - 2)));
}
double fac(int x) {
return (x < 2 ? 1 : x * factorial(x - 1));
}
void getSeries(SERIES _s, double _limit, int& _length, double *series) {
_length = 0;
switch (_s) {
case LOG: {
for (int i = 0; log(i) < _limit; i++) {
series[i] = log(i);
_length++;
}
break;
}
case EXP: {
for (int i = 0; exp(i) < _limit; i++) {
series[i] = exp(i);
_length++;
}
break;
}
case FIB: {
for (int i = 0; fib(i) < _limit; i++) {
series[i] = fib(i);
_length++;
}
break;
}
case FAC: {
for (int i = 0; fac(i) < _limit; i++) {
series[i] = fac(i);
_length++;
}
break;
}
}
}
double mean(double* _values, int length) {
double sum;
for (int i = 0; i < length; i++) {
sum += _values[i];
}
return (sum / length);
}
void printSeries(double* _series, int _length) {
for (int i = 0; i < _length; i++) {
cout << "[" << i << "]" << _series[i] << endl;
}
}
Main:
/*
* main.cpp
*/
#include <iostream>
#include "series.h"
using namespace std;
int main() {
double _limit;
int _length;
double* series = new double;
cout << "Series Calculator Application" << endl;
cout << "Please enter a limit:" << endl;
cin >> _limit;
cout << "Limit is " << _limit << endl;
getSeries(LOG, _limit, _length, series);
cout << "\nLOG Length is " << _length <<endl;
cout << "------------TEST(LOG)" << endl;
for(int i = 0; i < _length; i++){
cout << "[" << i << "]" << log(i) << endl;
}
cout << "------------ACTUAL(LOG)" << endl;
printSeries(series, _length);
getSeries(EXP, _limit, _length, series);
cout << "\nEXP Length is " << _length <<endl;
cout << "------------TEST(EXP)" << endl;
for(int i = 0; i < _length; i++){
cout << "[" << i << "]" << exp(i) << endl;
}
cout << "------------ACTUAL(EXP)" << endl;
printSeries(series, _length);
}
and when I run my main I get this from the console:
Series Calculator Application
Please enter a limit:
300
Limit is 300
LOG Length is 11
------------TEST(LOG)
[0]0
[1]0.833333
[2]2.66667
[3]7.5
[4]17.3333
[5]34.1667
[6]60
[7]96.8333
[8]146.667
[9]211.5
[10]293.333
------------ACTUAL(LOG)
[0]0
[1]0.833333
[2]2.66667
[3]7.5
[4]2.24151e-048
[5]1.96774e-259
[6]1.02756e-259
[7]96.8333
[8]146.667
[9]211.5
[10]293.333
EXP Length is 9
------------TEST(EXP)
[0]1
[1]2.70833
[2]7
[3]16.375
[4]34.3333
[5]65.375
[6]115
[7]189.708
[8]297
------------ACTUAL(EXP)
[0]1
[1]2.70833
[2]7
[3]16.375
[4]8.60084e-043
[5]1.56125e-259
[6]1.02899e-259
[7]189.708
[8]297
and there's my problem, as you can see, the actual implementation for elements 4, 5, and 6 does not match the test values. I have no idea how this happens. Please help!
When you allocate series:
double* series = new double;
This allocates a single double. Using it as an array and accessing any element other than index 0 will lead to undefined behavior.
You could consider using std::vector<double> and add elements as needed.
Need to bubble sort 100 random numbers with range from -100 to 100 from high to low while maintaining the current decimal place precision. I have a bubble sort function but am not sure how to call it from within another function.
#include "stdafx.h"
#include <fstream> // writing data to disk
#include <cstdlib> // standard general utilities library "# generator"
#include <ctime> // convert time value to string
#include <iostream>
#include <iomanip> // set precision
using namespace std;
// Functions
void number_Generator();
void bubbleSort (double *array, double length)
{
int i,j;
for (i=0;i<100;i++)
{
for (j=0;j<i;j++)
{
if(array[i]>array[j])
{
int temp = array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
system("pause");
cout.precision (6);
number_Generator();
}
// Number Generator Function
void number_Generator()
{
double Final_Avg = 0;
double Random_Cap = 100;
double Samples_To_Create = 100;
srand((unsigned)time(0));
double rndDbl;
int rndInt;
double rndAvg = 0, rndMin = 0, rndMax = 0;
int counter = 0;
double temp = 0;
double dblRanAry[100];
Final_Avg = rndAvg / counter; // final average to display
double lDbl=0, hDbl=Random_Cap;
int lInt = 0, hInt=1;
double dblRange=(hDbl-lDbl)+1;
int intRange=(hInt-lInt)+1;
for(int index=0; index<Samples_To_Create; index++)
{
rndInt = lInt+int(intRange*rand()/(RAND_MAX + 1.0));
rndDbl = lDbl+double(dblRange*rand()/(RAND_MAX + 1.0));
// random number if statement
if (rndInt == 0){
rndDbl = -(rndDbl);
} //start of Min/Max if statements
if (rndMin == 0){
rndMin = rndDbl;
}
else if (rndDbl < rndMin){
rndMin = rndDbl;
}
if (rndMax == 0){
rndMax = rndDbl;
}
else if (rndDbl > rndMax){
rndMax = rndDbl;
} //end of Min Max if statements
temp = rndDbl;
rndAvg += temp;
dblRanAry[counter] = temp;
counter++;
cout.precision (6);
cout << fixed << " " << rndDbl << endl;
}
cout << " " << endl
<< "The average = " << fixed << rndAvg/counter << endl
<< " " << endl
<< "The Min = " << fixed << rndMin << endl
<< " " << endl
<< "The Max = " << fixed << rndMax << endl
<< " " << endl;
} // end of number generator function
You need to do several things:
add the sort function call as shown below:
int _tmain(int argc, _TCHAR* argv[])
{
system("pause");
cout.precision (6);
int dblArray[100] = {0.0}; //these change are explained below
number_Generator(dblArray, 100); //100 means generate 100 random numbers
//remove double dblRanAry[100] inside the generator;
bubbleSort (dblArray, 100) ;
}
change the prototype of number_Generator to
void number_Generator(double dblArray[], int length);
your number_Generator should either
return an array that stores those random numbers to main or
stores those numbers in a global array or
pass the array into it and stores numbers as I did above.
You may also change your number_Generator to meet the prototype change.
Additionally:
void bubbleSort (double *array, int length)
{ //^^array length is int, not double
for (int i = 0; i < length; i++)
{ //^^use length, not hardcoded 100
for (int j = 0; j < i; j++)
{
if(array[i] > array[j])
{
double temp = array[i];
//since array elements are double, not int
array[i] = array[j];
array[j] = temp;
}
}
}
}