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++;
}
}
}
Related
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;
}
}
I have problem with recursive functions.
I have to build a recursive function which creates an array of integer values corresponding to the digits of a given number.
For example, if I input a number like 3562, it should look like :
myArray[0] = 3
myArray[1] = 5
myArray[2] = 6
myArray[3] = 2
Here is my code :
#include <iostream>
using namespace std;
int myFunction(int num, int lenOfNum);
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
cout << myFunction(number, lengthCount) << endl;
}
int myFunction(int num, int lenOfNum){
int arr[lenOfNum];
if(num > 0){
for(int i = 0; i < lenOfNum; i++){
arr[i] = num/=10;
cout << "arr[" << i + 1 << " ]= " << arr[i] << endl;
}
return myFunction(num, lenOfNum);
}
else if(num == 0){
return 0;
} else;
}
The problem with your code is that you are calling int arr[lenOfNum] in each method call, which in short creates an array with a new reference to a memory location that can store lenOfNum integers.
To solve this, we declare the array in the main method and pass it as a parameter to the function.
int main() {
// somewhere in main after reading lenOfNum
int arr[lenOfNum];
// somewhere in main after declaring an array
myFunction(arr, number, lengthCount - 1);
}
and myFunction as
void myFunction(int *arr, int num, int idx) {
if (idx < 0) return; // you've completed processing the num
else if (num == 0) {
arr[0] = 0;
return;
}
arr[idx--] = num % 10;
myFunction(arr, num / 10, idx);
}
Using vector and rest part of your example
#include <iostream>
using namespace std;
void myFunction(vector<int> &arr, int num, int lenOfNum){
if (num < 0) {
return;
}
else if (num == 0) {
return;
}
int next_idx = lenOfNum - 1;
int digit = num % 10;
arr[next_idx] = digit;
myFunction(arr, num / 10, next_idx);
}
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
auto arr = vector<int>(lengthCount, 0);
myFunction(arr, number, lengthCount);
for(int i = 0; i < arr.size(); i++){
cout << "arr[" << i << " ]= " << arr[i] << endl;
}
}
Works for positive numbers
#include <vector>
#include <stdio.h>
std::vector<int> myFunction(int num)
{
std::vector<int> ret;
int irec = num / 10;
if (irec > 0)
ret = myFunction(irec);
ret.push_back('0' + (num % 10));
return ret;
}
int main(int argc, char *argv[])
{
std::vector<int> res = myFunction(539);
for(unsigned int i = 0; i < res.size(); i++)
printf("%c,", res[i]);
}
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);
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;
}
}
}
}