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 6 years ago.
Improve this question
Hi i'm trying to Write a program in C++ to, generate and print 20 random numbers, between 0 to 999, and do the following operations without using inbuilt functions, find and print the: min value, max value, average, median, standard deviation, variance. Do a binary search on the 15th element. Please help me with the code.
So far i've done this much
#include
#include
#include
using namespace std;
void minimum(int[], int);
void maximum (int[], int);
void average(int[], int);
void median(int[], int);
void mean(int[], int);
void sort(int[], int);
int ra()
{
int r = rand() % 1000;
return r;
}
int main ()
{
srand(time(NULL));
ra();
int array[20];
int num=20;
for (unsigned int i = 0; i < num; i++)
{
array[i] = ra();
cout << "Index: " << i << ", random number: " << array[i] << endl;
}
minimum();
new_array[20];
num=20;
for (unsigned int i = 0; i < num; i++)
{
new_array[i] = new_array();
cout << "Index: " << i << ", random number: " << minimum << endl;
}
return 0;
}
void minimum(int new_array[], int num)
{
for (unsigned int i = 0; i < num; i++)
if (new_array[i] minimum)
minimum = new_array[i];
cout << "Maximum value: " << minimum << endl;
}
void maximum (int new_array[], int num)
{
for (unsigned int i = 0; i < num; i++)
if (new_array[i] > maximum)
maximum = new_array[i];
cout << "Maximum value: " << maximum << endl;
return 0;
}
void median(int new_array[], int num)
{
//CALCULATE THE MEDIAN (middle number)
if(num % 2 != 0){// is the # of elements odd?
int temp = ((num+1)/2)-1;
cout << "The median is " << new_array[temp] << endl;
}
else{// then it's even! :)
cout << "The median is "<< new_array[(num/2)-1]<<new_array[num/2]< endl;
}
mean(new_array, num);
}
void sort(int new_array[], int num)
{
//ARRANGE VALUES
for(int x=0; x<num; x++){
for(int y=0; y<num-1; y++){
if(new_array[y]>new_array[y+1]){
int temp = new_array[y+1];
new_array[y+1] = new_array[y];
new_array[y] = temp;
}
}
}
cout << "List: ";
for(int i =0; i<num; i++){
cout << new_array[i] << " ";
}
cout << "\n";
median(new_array, num);
}
void average_(int new_array[], int nums)
{
float sum;
for (unsigned int i = 0; i < 20; ++i)
{
sum+=num;
}
cout << "Average value: " << average_/num << endl;
}
Please tell the necessary corrections
You have a ways to go, your code does not do any of the things you want yet. However, you mentioned that you are a beginner so I fixed your code and set up a basic structure of how to get going. I left comments on what I changed and what you need to do. That being said, I don't know what you mean by "Do a binary search on the 15th element"
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int ra()
{
// You wanted a number between 0 and 999 inclusive so do not add 1
// Instead do a modulus of 1000
int r = rand() % 1000;
return r;
}
int main ()
{
// Do this to get different random numbers each time you run your program
srand(time(NULL));
// You have to call ra as a function. Do this by writing: ra()
// Here I am storing 20 random numbers in an array
int nums[20];
for (unsigned int i = 0; i < 20; ++i)
{
nums[i] = ra();
cout << "Index: " << i << ", random number: " << nums[i] << endl;
}
// Iterate to find the minimum number
int minimum = nums[0];
for (unsigned int i = 1; i < 20; ++i)
if (nums[i] < minimum)
minimum = nums[i];
cout << "Minimum value: " << minimum << endl;
// TODO: Find the maximum in basically the same way
// TODO: Find the average by summing all numbers then dividing by 20
// TODO: Find the median by sorting nums and taking the average of the two center elements
// TODO: etc.
return 0;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int r;
int ra;
int i=0;
int ra(){
r = (rand() % 999) + 1;
return r;
}
int main ()
{
int random_;
srand((int)time(0));
while (i++ < 20)
{
random_ = r;
cout<< random_<<endl;
}
return 0;
}
Related
`
#include <iostream>
#include <iomanip>
using namespace std;
void getGrades(double g[], const int SIZE)
{
cout << "Please enter " << SIZE << " grades:" << endl;
for(int i = 0; i < SIZE; i++)
{
cin >> g[i];
}
}
double getAverage(double g[], const int SIZE)
{
int total = 0;
for(int i = 0; i < SIZE; i++)
{
total += g[i];
}
return total/SIZE;
}
void findDropInfo(double g[], const int SIZE, int &lowest, double average)
{
int total = 0;
lowest = g[0];
for(int i = 1; i < SIZE; i++)
{
if (lowest > g[i]) {
lowest = g[i];
}
}
average = (total - lowest)/SIZE;
return average;
}
void printData(double g[], int lowest, double average, double avg_before)
{
cout << "The 5 grades entered by the user are:" << endl;
cout << g[];
cout << "Grade dropped: " << lowest << endl;
cout << "Final Average: " << average << endl;
cout << "Average before drop: " << avg_before << endl;
}
// TODO: Complete the function definitions
int main()
{
const int SIZE = 5;
double grades[SIZE];
int lowest;
double avg,
avgBeforeDrop;
// TODO: Add function calls
getGrades(grades[SIZE], SIZE);
getAverage(grades[SIZE], SIZE);
findDropInfo(grades[SIZE], SIZE, lowest, avg);
printData(grades[SIZE], lowest, avg, avgBeforeDrop);
return 0;
}
`
Whenever I run the program, I get multiple errors saying there's no matching candidate function. I'm not sure if the problems are in the functions themselves or in the function calls, but from what I know the functions themselves should be fine. I'm also told there's an expected expression in g[] but I' not sure what's wrong there either, as it's meant to be empty.
Most issues have already been resolved in the comments, but note: cout << g[] does not print the elements of g.
The way to do this is
char separator = /* the character you want to use to separate the printed elements of g */
for (int i = 0; i < SIZE; i++)
{
cout << g[i] << separator;
}
if (separator != '\n') cout << '\n'; //this is to put the next print on the next line
I would put this as a comment but I don't have enough reputation :|
I finished this code homework assignment tonight. I thought I was done, but I just realized that my "Average" value is coming out wrong with certain values. For example: When my professor entered the values 22, 66, 45.1, and 88 he got an "Average" of 55.27. However, when I enter those values in my program, I get an "Average" of 55.25. I have no idea what I am doing wrong. I was pretty confident in my program until I noticed that flaw. My program is due at midnight, so I am clueless on how to fix it. Any tips will be greatly appreciated!
Code Prompt: "Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores. Once all the scores are entered, the array should be passed to a function that sorts them in ascending order. Another function should be called that calculates the average score. The program should display the sorted list of scores and averages with appropriate headings. Use pointer notation rather than array notation whenever possible."
Professor Notes: The book only states, "Input Validation: Do not accept negative numbers for test scores." We also need to have input validation for the number of scores. If it is negative, including 0, the program halts, we should consider this situation for 'counter' not to be negative while we have a loop to enter numbers. So negative numbers should be rejected for the number of scores and the values of scores.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
void showArray(double* array, int size);
double averageArray(double* array, int size);
void orderArray(double* array, int size);
int main()
{
double* scores = nullptr;
int counter;
double numberOfScores;
cout << "\nHow many test scores will you enter? ";
cin >> numberOfScores;
if (numberOfScores < 0) {
cout << "The number cannot be negative.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
if (numberOfScores == 0) {
cout << "You must enter a number greater than zero.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
scores = new double[numberOfScores];
for (counter = 0; counter < numberOfScores; counter++) {
cout << "Enter test score " << (counter + 1) << ": ";
cin >> *(scores + counter);
if (*(scores + counter) < 0) {
cout << "Negative scores are not allowed. " << endl
<< "Enter another score for this test : ";
cin >> *(scores + counter);
}
}
orderArray(scores, counter);
cout << "\nThe test scores in ascending order, and their average, are: " << endl
<< endl;
cout << " Score" << endl;
cout << " -----" << endl
<< endl;
showArray(scores, counter);
cout << "\nAverage Score: "
<< " " << averageArray(scores, counter) << endl
<< endl;
cout << "Press any key to continue...";
delete[] scores;
scores = nullptr;
system("pause>0");
}
void orderArray(double* array, int size)
{
int counterx;
int minIndex;
int minValue;
for (counterx = 0; counterx < (size - 1); counterx++) {
minIndex = counterx;
minValue = *(array + counterx);
for (int index = counterx + 1; index < size; index++) {
if (*(array + index) < minValue) {
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + counterx);
*(array + counterx) = minValue;
}
}
double averageArray(double* array, int size)
{
int x;
double total{};
for (x = 0; x < size; x++) {
total += *(array + x);
}
double average = total / size;
return average;
}
void showArray(double* array, int size)
{
for (int i = 0; i < size; i++) {
cout << " " << *(array + i) << endl;
}
}
I try to start my answers with a brief code review:
#include <iostream>
#include <iomanip>
using namespace std; // Bad practice; avoid
void showArray(double* array, int size);
double averageArray(double* array, int size);
void orderArray(double* array, int size);
int main()
{
double* scores = nullptr;
int counter;
double numberOfScores;
cout << "\nHow many test scores will you enter? ";
cin >> numberOfScores;
// This is not input validation, I can enter two consecutive bad values,
// and the second one will be accepted.
if (numberOfScores < 0) {
// Weird formatting, this blank line
cout << "The number cannot be negative.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
// The homework, as presented, doesn't say you have to treat 0 differently.
if (numberOfScores == 0) {
cout << "You must enter a number greater than zero.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
scores = new double[numberOfScores];
// Declare your loop counter in the loop
for (counter = 0; counter < numberOfScores; counter++) {
cout << "Enter test score " << (counter + 1) << ": ";
cin >> *(scores + counter);
if (*(scores + counter) < 0) {
cout << "Negative scores are not allowed. " << endl
<< "Enter another score for this test : ";
cin >> *(scores + counter);
}
}
orderArray(scores, counter); // Why not use numberOfScores?
cout << "\nThe test scores in ascending order, and their average, are: " << endl
<< endl;
cout << " Score" << endl;
cout << " -----" << endl
<< endl;
showArray(scores, counter); // Same as above.
cout << "\nAverage Score: "
<< " " << averageArray(scores, counter) << endl
<< endl;
cout << "Press any key to continue...";
delete[] scores;
scores = nullptr;
system("pause>0"); // Meh, I suppose if you're on VS
}
void orderArray(double* array, int size)
{
int counterx;
int minIndex;
int minValue; // Unnecessary, and also the culprit
// This looks like selection sort
for (counterx = 0; counterx < (size - 1); counterx++) {
minIndex = counterx;
minValue = *(array + counterx);
for (int index = counterx + 1; index < size; index++) {
if (*(array + index) < minValue) {
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + counterx);
*(array + counterx) = minValue;
}
}
double averageArray(double* array, int size)
{
int x;
double total{};
for (x = 0; x < size; x++) {
total += *(array + x);
}
double average = total / size;
return average;
}
void showArray(double* array, int size)
{
for (int i = 0; i < size; i++) {
cout << " " << *(array + i) << endl;
}
}
When you are sorting your array, you keep track of the minValue as an int and not a double. That's why your average of the sample input is incorrect. 45.1 is truncated to 45 for your calculations. You don't need to keep track of the minValue at all. Knowing where the minimum is, and where it needs to go is sufficient.
But as I pointed out, there are some other serious problems with your code, namely, your [lack of] input validation. Currently, if I enter two consecutive bad numbers, the second one will be accepted no matter what. You need a loop that will not exit until a good value is entered. It appears that you are allowed to assume that it's always a number at least, and not frisbee or any other non-numeric value.
Below is an example of what your program could look like if your professor decides to teach you C++. It requires that you compile to the C++17 standard. I don't know what compiler you're using, but it appears to be Visual Studio Community. I'm not very familiar with that IDE, but I imagine it's easy enough to set in the project settings.
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
// Assumes a number is always entered
double positive_value_prompt(const std::string& prompt) {
double num;
std::cout << prompt;
do {
std::cin >> num;
if (num <= 0) {
std::cerr << "Value must be positive.\n";
}
} while (num <= 0);
return num;
}
int main() {
// Declare variables when you need them.
double numberOfScores =
positive_value_prompt("How many test scores will you enter? ");
std::vector<double> scores;
for (int counter = 0; counter < numberOfScores; counter++) {
scores.push_back(positive_value_prompt("Enter test score: "));
}
std::sort(scores.begin(), scores.end());
for (const auto& i : scores) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "\nAverage Score: "
<< std::reduce(
scores.begin(), scores.end(), 0.0,
[size = scores.size()](auto mean, const auto& val) mutable {
return mean += val / size;
})
<< '\n';
}
And here's an example of selection sort where you don't have to worry about the minimum value. It requires that you compile to C++20. You can see the code running here.
#include <iostream>
#include <random>
#include <vector>
void selection_sort(std::vector<int>& vec) {
for (int i = 0; i < std::ssize(vec); ++i) {
int minIdx = i;
for (int j = i + 1; j < std::ssize(vec); ++j) {
if (vec[j] < vec[minIdx]) {
minIdx = j;
}
}
int tmp = vec[i];
vec[i] = vec[minIdx];
vec[minIdx] = tmp;
}
}
void print(const std::vector<int>& v) {
for (const auto& i : v) {
std::cout << i << ' ';
}
std::cout << '\n';
}
int main() {
std::mt19937 prng(std::random_device{}());
std::uniform_int_distribution<int> dist(1, 1000);
std::vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(dist(prng));
}
print(v);
selection_sort(v);
print(v);
}
I opted not to give your code the 'light touch' treatment because than I would have done your homework for you, and that's just not something I do. However, the logic shown should still be able to guide you toward a working solution.
I have a code that generates 10 random numbers and I need to calculate the sum and product of the non-zero numbers and display which numbers have been multiplied. I already have most of the code but I have no idea how to multiply numbers that are nonzero and then display them. Can someone help me?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
int main()
{
cout << "draws 10 numbers:" << endl;
Sleep(1000);
cout << endl;
srand(time(0));
int sum=0;
int product=1;
for(int i=0, value=0; i<10; i++, sum+=value, product*=value)
{
value = rand()%10+0;
Sleep(1000);
cout << value << endl;
}
Sleep(1000);
cout << "the sum is " << sum <<endl;
cout << "the product is " << product <<endl;
return 0;
}
To start, it is easier to read and understand if we move the addition and multiplication out of the for loop header.
int sum = 0;
int value = 1;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
product *= value;
std::cout << value << std::::endl;
}
Next, we only want to do the multiplication if the value is not equal 0.
int sum = 0;
int value = 1;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
if(value != 0)
{
product *= value;
}
std::cout << value << std::::endl;
}
So the whole program looks like this.
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
std::cout << "draws 10 numbers:" << std::endl;
srand(time(0));
int sum = 0;
int product = 1;
int multiplied = 0;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
if(value != 0)
{
product *= value;
multiplied += 1;
}
std::cout << value << " ";
}
std::cout << std::endl;
std::cout << "the sum is " << sum << std::endl;
std::cout << "the product is " << product << std::endl;
std::cout << "numbers multiplied is " << multiplied << std::endl;
return EXIT_SUCCESS;
}
I am trying to have the program output the winner in a candidate race when trying to go through the array to get the highest count instead of the highest it gets the next highest from zero, and i feel like i have tried everything.
I keep trying to change things around in the find winner function but nothing seems to be working I dont see what i am doing wrong please help.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
//User inputs data for candidates and votes.
//Output Candidates, votes, and percentage.
//Names that will be used are johnson, miller, duffy, robinson, ashtony
//count of votes to use = 5000, 4000, 6000, 2500, 1800, total 19300
//Percentages that will be used for candidates= 25.91, 20.73, 31.09, 12.95, 9.33
int findWinner(int votes[]);
void Results(string candidates[], int votes[]);
double Percentage(int votes[], int vote);
int tester[5] = {};
const int NUMBER_OF_CANDIDATES = 5;
int main()
{
string candidates[NUMBER_OF_CANDIDATES];
int votes[NUMBER_OF_CANDIDATES];
cout << "Enter 5 Candidates with their votes ex: DelBosque 7000: ";
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
cin >> candidates[i] >> votes[i];
}
cout << "Candidate Votes Received % of Total Votes" << endl;
Results(candidates, votes);
cout << "The Winner of the Election is " << candidates[findWinner(votes)] <<
endl;
return 0;
}
double Percentage(int votes[], int vote){
int sumOfVotes = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
sumOfVotes += votes[i];
}
double percent = static_cast<double>(vote) / sumOfVotes;
double votePercent = 0;
votePercent = percent * 100;
std::cout << std:: fixed;
std::cout << std:: setprecision(2);
std::cout << votePercent;
return 0;
};
void Results(string candidates[], int votes[]){
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
cout << candidates[i] << setw(15) << votes[i] << setw(15);
int percent = Percentage(votes, votes[i]);
cout << percent << "%" << endl;
};
};
// You are returning the number of votes. Shouldn't you be returning the
// index referenced by the highest number of votes?
int findWinner(int votes[]){
int index = 0;
int winner = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
if (votes[i] > winner)
winner = votes[i];
index = i;
};
return index;
};
You need both the following lines under the if condition.
winner = votes[i];
index = i;
like:
if (votes[i] > winner)
{
winner = votes[i];
index = i;
}
What you have is equivalent to:
if (votes[i] > winner)
{
winner = votes[i];
}
index = i;
which is not correct.
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 6 years ago.
Improve this question
I'm writing a program that calculates the batting averages of a user defined number of players. The program displays the name of a player, their number of times at bat, number of hits, and their batting average. Finally, it displays the total number of times the players were at bat, the total number of hits, and the overall average. For some reason, the functions that calculate the individual player average and overall average are returning 0. It's probably something small, but I'm stumped as to how to try and fix it.
//Batting Average Calculator
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//Create Structure
struct Record
{
string name;
int AB;
int hit;
double avg;
};
int getSize(int);
void getData(Record[], int );
int calculateTotalAB(Record[], int, int);
int calculateTotalHit(Record[], int, int);
double calculateTotalAvg(Record[], int, double);
void calculateAvg(Record[], int);
void display(Record[], int, int , int, double);
int main()
{
const int MaxSize = 50;
Record players[MaxSize];
int size = 0;
int totalAB = 0;
int totalHit = 0;
double totalAvg = 0;
size = getSize(size);
getData(players, size);
totalAB = calculateTotalAB(players, size, totalAB);
totalHit = calculateTotalHit(players, size, totalHit);
calculateAvg(players,size);
totalAvg = calculateTotalAvg(players, size, totalAvg);
display(players, size, totalHit, totalAB, totalAvg);
}
//get number of players to be calculated
int getSize(int size)
{
cout << "Please enter the number of players on the team: ";
cin >> size;
return size;
}
//get Player name, AB, and hit
void getData(Record players[], int size)
{
string dummy;
getline(cin, dummy);
for (int i = 0; i < size; i++)
{
cout << "Please input the name of student " << i + 1 << ": ";
getline(cin, players[i].name);
cout << "Please input the number of times "<< players[i].name << " was at bat: ";
cin >> players[i].AB;
cout << "Please input the number of hits for " << players[i].name << ": ";
cin >> players[i].hit;
cout << " " << endl;
getline(cin, dummy);
}
}
int calculateTotalAB(Record players[], int size, int totalAB)
{
for (int i = 0; i < size; i++)
{
totalAB = totalAB + players[i].AB;
}
return totalAB;
}
int calculateTotalHit(Record players[], int size, int totalHit)
{
for (int i = 0; i < size; i++)
{
totalHit = totalHit + players[i].hit;
}
return totalHit;
}
void calculateAvg(Record players[], int size)
{
for (int i = 0; i < size; i++)
{
players[i].avg = players[i].hit / players[i].AB;
}
}
double calculateTotalAvg(Record players[], int size, double totalAvg)
{
double j = 0;
for (int i = 0; i < size; i++)
{
j = j + players[i].avg;
}
totalAvg = j / size;
return totalAvg;
}
void display(Record players[], int size, int totalHit, int totalAB, double totalAvg)
{
cout << fixed << showpoint << setprecision(3);
cout << "Player AB Hit Avg" << endl;
cout << " " << endl;
for (int i = 0; i < size; i++)
{
cout << players[i].name << setw(8) << players[i].AB << setw(5) << players[i].hit << setw(5) << players[i].avg;
}
cout << " " << endl;
cout << "Totals " << totalAB << " " << totalHit << " " << totalAvg << endl;
}
You are dividing an int by an int, which is calculated as an int, and storing it in a double. What you have to do is explicitly cast at least one of your int values to a double first, like this:
void calculateAvg(Record players[], int size)
{
for (int i = 0; i < size; i++)
{
players[i].avg = players[i].hit / (double) players[i].AB;
}
}