Relatively new to C++ and this has been bugging me for a while. I'm trying to write a program that will do different things depending on what random number is generated.
To explain what I'm trying to do simply, lets pretend I'm creating a list of athletes and start by randomly generating their heights within a certain range. Easy to do no problem. Say then I want to generate their weight, based on their height. This is where things get messy. For some reason I can't figure out, the program is randomly generating the weight based on a different height than the one it returns in the first place. I just don't get it.
Anyway, here is a piece of (very simplified) sample code that hopefully shows what I'm trying to do. I'm sure I'm missing something obvious but I just can't seem to figure it out.
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;
int random(int min, int max, int base)
{
int random = (rand() % (max - min) + base);
return random;
}
int height()
{
int height = random(1, 24, 60);
return height;
}
int weight()
{
int weight = height() * 2.77;
return weight;
}
void main()
{
srand ((unsigned int)time(0));
int n = 1;
while (n <= 10)
{
cout << height() << " and " << weight() << endl;
++n;
}
return;
}
weight is calling height again, and it will obviously be generating a different number (that's the whole point of an RNG :) ).
To obtain the effect you want you could:
change weight to accept the the height as a parameter; then, in the main, at each iteration save the value returned by height in a temporary variable and pass it to height to obtain the corresponding height;
int weight(int height)
{
return height*2.77;
}
// ... inside the main ...
while (n <= 10)
{
int curHeight=height();
cout << curHeight << " and " << weight(curHeight) << endl;
++n;
}
move height and weight to a class, which will store height as a private field, adding a nextPerson member that will update the internal field to a new random value.
class RandomPersonGenerator
{
int curHeight;
public:
RandomPersonGenerator()
{
nextPerson();
}
int height() { return curHeight; }
int weight() { return height()*2.77; }
void nextPerson()
{
curHeight=random(1, 24, 60);
}
};
// ... inside the main ...
RandomPersonGenerator rpg;
while (n <= 10)
{
rpg.nextPerson();
cout << rpg.height() << " and " << rpg.weight() << endl;
++n;
}
(by the way, it's int main, not void main, and a for cycle is more appropriate than while in this situation)
It's quite easy. You call height() in your weight() function. That means you're getting a new random value for the height. What you have to do is to modify your weight() so that it can pass through a height parameter and calculate the weight based on it (and not on a new random value).
Your new height() function would look as follow:
int weight(int height)
{
int weight = height * 2.77;
return weight;
}
In your main():
while (n <= 10)
{
int h = height();
int w = weight(h);
cout << h << " and " << w << endl;
++n;
}
Related
Here is my code I have looked up what to do multiple times and still haven't figured out what to do.
It keeps giving me this error: C++ expression must be an lvalue or a function designator with the part of the code :
avg_score = (float)*&get_average_score(score_1, score_2, score_3);`
how can i fix the error?
the original error was cannot convert a void to a float
avg_score = get_average_score(score_1, score_2, score_3);
how can i fix the error?`
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <ctime>
using namespace std;
void print_scores(int score_1, int score_2, int score_3);
void get_average_score(int score_1, int score_2, int score_3);
int main()
{
srand(time(NULL));
int score_1, score_2, score_3;
float avg_score;
score_1 = rand() % 21 + 20;
while (score_1 % 2 == 0)
{
score_1 = rand() % 21 + 20;
}
score_2 = rand() % 21 + 20;
score_3 = rand() % 21 + 20;
print_scores(score_1, score_2, score_3);
avg_score = (float)*&get_average_score(score_1, score_2, score_3);
cout << fixed << setprecision(1);
cout << "Average score = " << avg_score <<
endl;
return 0;
}
void print_scores(int score_1, int score_2, int score_3)
{
cout << "score 1 = " << score_1 << endl << "score 2 = " << score_2 << endl
<< "score 3 = " << score_3 << endl;
}
void get_average_score(int score_1, int score_2, int score_3)
{
(float)(score_1 + score_2 + score_3) / (float)3;
}
Your first mistake lies in the fact that you are trying to get a function that does not return a value to return a value. You've tried to reference a pointer *& which is not how you should be handling this as
1) you've tried to reference a pointer but instead you've done it on a function
2) you want a value, not a pointer so its the wrong approach.
If you need to use pointers (because thats the task at hand) then what you need to do is pass a reference to avg_score into your function.
void get_average_score(float * avg_score, int score_1, int score_2, int score_3)
{
*avg_score = (score_1 + score_2 + score_3) / 3.0;
}
and call it in main with:
get_average_score(&avg_score, score_1, score_2, score_3);
and dont forget to update the header declaration:
void get_average_score(float * avg_score, int score_1, int score_2, int score_3);
If you don't have to use pointers the easiest fix is to actually return a value.
Declare the function as type float :
float get_average_score(int score_1, int score_2, int score_3);
and edit the get_average_score function to be:
float get_average_score(int score_1, int score_2, int score_3)
{
return (score_1 + score_2 + score_3) / 3.0;
}
and get rid of (float)*& from main.
This means your function will return a float value that will be stored in avg_score on return.
Also note, by changing the denominator to 3.0 instead of 3 you don't need to don't need to type cast the result as a float.
Your coding style does come off as a little basic (which is ok, everyone has to start somewhere) but you have room for improvement, so take the time to learn now rather than struggling later (trust me it makes life easy in the long run).
Rather than making a function that will only work when you are averaging 3 numbers why not make a more modular function that would work for as many numbers as you want!
Try learning how to use vectors! If you're coming from C its kinda like an array but can be dynamically allocated i.e. any size you want.
Have a look around the net for some tutorials on what vectors are and how to use them.
I won't write out the code for this because you should learn how to do it your self (trust me you'll understand it better) but basically using a vector of int's std::vector<int> you can iterate through them all and add each element together and then at the end divide by the total number of elements (the number of iterations you do) to get your average!
**obviously theres a limit but thats a limit of your computer... *
I'm a programming student, and for a project I'm working on, on of the things I have to do is compute the median value of a vector of int values and must be done by passing it through functions. Also the vector is initially generated randomly using the C++ random generator mt19937 which i have already written down in my code.I'm to do this using the sort function and vector member functions such as .begin(), .end(), and .size().
I'm supposed to make sure I find the median value of the vector and then output it
And I'm Stuck, below I have included my attempt. So where am I going wrong? I would appreciate if you would be willing to give me some pointers or resources to get going in the right direction.
Code:
#include<iostream>
#include<vector>
#include<cstdlib>
#include<ctime>
#include<random>
#include<vector>
#include<cstdlib>
#include<ctime>
#include<random>
using namespace std;
double find_median(vector<double>);
double find_median(vector<double> len)
{
{
int i;
double temp;
int n=len.size();
int mid;
double median;
bool swap;
do
{
swap = false;
for (i = 0; i< len.size()-1; i++)
{
if (len[i] > len[i + 1])
{
temp = len[i];
len[i] = len[i + 1];
len[i + 1] = temp;
swap = true;
}
}
}
while (swap);
for (i=0; i<len.size(); i++)
{
if (len[i]>len[i+1])
{
temp=len[i];
len[i]=len[i+1];
len[i+1]=temp;
}
mid=len.size()/2;
if (mid%2==0)
{
median= len[i]+len[i+1];
}
else
{
median= (len[i]+0.5);
}
}
return median;
}
}
int main()
{
int n,i;
cout<<"Input the vector size: "<<endl;
cin>>n;
vector <double> foo(n);
mt19937 rand_generator;
rand_generator.seed(time(0));
uniform_real_distribution<double> rand_distribution(0,0.8);
cout<<"original vector: "<<" ";
for (i=0; i<n; i++)
{
double rand_num=rand_distribution(rand_generator);
foo[i]=rand_num;
cout<<foo[i]<<" ";
}
double median;
median=find_median(foo);
cout<<endl;
cout<<"The median of the vector is: "<<" ";
cout<<median<<endl;
}
The median is given by
const auto median_it = len.begin() + len.size() / 2;
std::nth_element(len.begin(), median_it , len.end());
auto median = *median_it;
For even numbers (size of vector) you need to be a bit more precise. E.g., you can use
assert(!len.empty());
if (len.size() % 2 == 0) {
const auto median_it1 = len.begin() + len.size() / 2 - 1;
const auto median_it2 = len.begin() + len.size() / 2;
std::nth_element(len.begin(), median_it1 , len.end());
const auto e1 = *median_it1;
std::nth_element(len.begin(), median_it2 , len.end());
const auto e2 = *median_it2;
return (e1 + e2) / 2;
} else {
const auto median_it = len.begin() + len.size() / 2;
std::nth_element(len.begin(), median_it , len.end());
return *median_it;
}
There are of course many different ways how we can get element e1. We could also use max or whatever we want. But this line is important because nth_element only places the nth element correctly, the remaining elements are ordered before or after this element, depending on whether they are larger or smaller. This range is unsorted.
This code is guaranteed to have linear complexity on average, i.e., O(N), therefore it is asymptotically better than sort, which is O(N log N).
Regarding your code:
for (i=0; i<len.size(); i++){
if (len[i]>len[i+1])
This will not work, as you access len[len.size()] in the last iteration which does not exist.
std::sort(len.begin(), len.end());
double median = len[len.size() / 2];
will do it. You might need to take the average of the middle two elements if size() is even, depending on your requirements:
0.5 * (len[len.size() / 2 - 1] + len[len.size() / 2]);
Instead of trying to do everything at once, you should start with simple test cases and work upwards:
#include<vector>
double find_median(std::vector<double> len);
// Return the number of failures - shell interprets 0 as 'success',
// which suits us perfectly.
int main()
{
return find_median({0, 1, 1, 2}) != 1;
}
This already fails with your code (even after fixing i to be an unsigned type), so you could start debugging (even 'dry' debugging, where you trace the code through on paper; that's probably enough here).
I do note that with a smaller test case, such as {0, 1, 2}, I get a crash rather than merely failing the test, so there's something that really needs to be fixed.
Let's replace the implementation with one based on overseas's answer:
#include <algorithm>
#include <limits>
#include <vector>
double find_median(std::vector<double> len)
{
if (len.size() < 1)
return std::numeric_limits<double>::signaling_NaN();
const auto alpha = len.begin();
const auto omega = len.end();
// Find the two middle positions (they will be the same if size is odd)
const auto i1 = alpha + (len.size()-1) / 2;
const auto i2 = alpha + len.size() / 2;
// Partial sort to place the correct elements at those indexes (it's okay to modify the vector,
// as we've been given a copy; otherwise, we could use std::partial_sort_copy to populate a
// temporary vector).
std::nth_element(alpha, i1, omega);
std::nth_element(i1, i2, omega);
return 0.5 * (*i1 + *i2);
}
Now, our test passes. We can write a helper method to allow us to create more tests:
#include <iostream>
bool test_median(const std::vector<double>& v, double expected)
{
auto actual = find_median(v);
if (abs(expected - actual) > 0.01) {
std::cerr << actual << " - expected " << expected << std::endl;
return true;
} else {
std::cout << actual << std::endl;
return false;
}
}
int main()
{
return test_median({0, 1, 1, 2}, 1)
+ test_median({5}, 5)
+ test_median({5, 5, 5, 0, 0, 0, 1, 2}, 1.5);
}
Once you have the simple test cases working, you can manage more complex ones. Only then is it time to create a large array of random values to see how well it scales:
#include <ctime>
#include <functional>
#include <random>
int main(int argc, char **argv)
{
std::vector<double> foo;
const int n = argc > 1 ? std::stoi(argv[1]) : 10;
foo.reserve(n);
std::mt19937 rand_generator(std::time(0));
std::uniform_real_distribution<double> rand_distribution(0,0.8);
std::generate_n(std::back_inserter(foo), n, std::bind(rand_distribution, rand_generator));
std::cout << "Vector:";
for (auto v: foo)
std::cout << ' ' << v;
std::cout << "\nMedian = " << find_median(foo) << std::endl;
}
(I've taken the number of elements as a command-line argument; that's more convenient in my build than reading it from cin). Notice that instead of allocating n doubles in the vector, we simply reserve capacity for them, but don't create any until needed.
For fun and kicks, we can now make find_median() generic. I'll leave that as an exercise; I suggest you start with:
typename<class Iterator>
auto find_median(Iterator alpha, Iterator omega)
{
using value_type = typename Iterator::value_type;
if (alpha == omega)
return std::numeric_limits<value_type>::signaling_NaN();
}
Can you give me advice about precision of computing Taylor series for an exponent? We have a degree of exponent and a figure of precision calculating as imput data. We should recieve a calculating number with a given precision as output data. I wrote a program, but when I calculate an answer and compare it with embedded function's answer, it has differents. Can you advice me, how I can destroy a difference between answeres? formula of exponent's calculating
#include "stdafx.h"
#include "iostream"
#include <math.h>
#include <Windows.h>
#include <stdlib.h>
using namespace std;
int Factorial(int n);
double Taylor(double x, int q);
int main()
{
double res = 0;
int q = 0;
double number = 0;
cout << "Enter positive number" << "\n";
cin >> number;
cout << "Enter rounding error (precision)" << "\n";
cin >> q;
cout << "\n" << "\n";
res = Taylor(number, q);
cout << "Answer by Taylor : " << res;
cout << "Answer by embedded function: " << exp(number);
Sleep(25000);
return 0;
}
int Factorial(int n) {
int res = 1;
int i = 2;
if (n == 1 || n == 0)
return 1;
else
{
while (i <= n)
{
res *= i;
i++;
}
return res;
}
}
double Taylor(double x, int q) {
double res = 1;
double res1 = 0;
int i =1;
while (i)
{
res += (pow(x, i) / Factorial(i));
if (int(res*pow(10, q)) < (res*pow(10, q)))
{//rounding res below
if ( ( int (res * pow(10,q+1)) - int(res*pow(10, q))) <5 )
res1 = (int(res*pow(10, q))) * pow(10, (-q));
else
res1 = (int(res*pow(10, q))) * pow(10, (-q)) + pow(10,-q);
return res1;
}
i++;
}
}
There are two problems in your code. First, the factorial is very prone to overflow. Actually I dont know when overflow occurs for int factorials, but I remember that eg on usual pocket calculators x! overflows already for x==70. You probably dont need that high factorials, but still it is better to avoid that problem right from the start. If you look at the correction that needs to be added in each step: x^i / i! (maths notation) then you notice that this value is actually much smaller than x^i or i! respectively. Also you can calculate the value easily from the previous one by simply multiplying it by x/i.
Second, I dont understand your calculations for the precision. Maybe it is correct, but to be honest for me it looks too complicated to even try to understand it ;).
Here is how you can get the correct value:
#include <iostream>
#include <cmath>
struct taylor_result {
int iterations;
double value;
taylor_result() : iterations(0),value(0) {}
};
taylor_result taylor(double x,double eps = 1e-8){
taylor_result res;
double accu = 1; // calculate only the correction
// but not its individual terms
while(accu > eps){
res.value += accu;
res.iterations++;
accu *= (x / (res.iterations));
}
return res;
}
int main() {
std::cout << taylor(3.0).value << "\n";
std::cout << exp(3.0) << "\n";
}
Note that I used a struct to return the result, as you should pay attention to the number of iterations needed.
PS: see here for a modified code that lets you use a already calculated result to continue the series for better precision. Imho a nice solution should also provide a way to set a limit for the number of iterations, but this I leave for you to implement ;)
the point of this exercise is to multiply a digit of a number with its current position and then add it with the others. Example: 1234 = 1x4 + 2x3 + 3x2 + 4x1 .I did this code successfully using 2 parameters and now i'm trying to do it with 1. My idea was to use - return num + mult(a/10) * (a%10) and get the answer, , because from return num + mult(a/10) i get the values 1,2,3,4- (1 is for mult(1), 2 for mult(12), etc.) for num, but i noticed that this is only correct for mult(1) and then the recursion gets wrong values for mult(12), mult(123), mult(1234). My idea is to independently multiply the values from 'num' with a%10 . Sorry if i can't explain myself that well, but i'm still really new to programming.
#include <iostream>
using namespace std;
int mult(int a){
int num = 1;
if (a==0){
return 1;
}
return ((num + mult(a/10)) * (a%10));
}
int main()
{
int a = 1234;
cout << mult(a);
return 0;
}
I find this easier and more logically to do, Hope this helps lad.
int k=1;
int a=1234;
int sum=0;
while(a>0){
sum=sum+k*(a%10);
a=a/10;
k++;
}
If the goal is to do it with recursion and only one argument, you may achieve it with two functions. This is not optimal in terms of number of operations performed, though. Also, it's more of a math exercise than a programming one:
#include <iostream>
using namespace std;
int mult1(int a) {
if(a == 0) return 0;
return a % 10 + mult1(a / 10);
}
int mult(int a) {
if(a == 0) return 0;
return mult1(a) + mult(a / 10);
}
int main() {
int a = 1234;
cout << mult(a) << '\n';
return 0;
}
i am learning recursion in C++ and as practice i was trying to write binary to decimal converter with recursive function. In following code converter is working as it should:
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
int sum = 0;
int DecimalConversion (int power, int number){
int bit;
if (number == 0)
{
return 0;
}
bit = number % 10;
sum = sum + bit * pow(2, power);
number /= 10;
power++;
DecimalConversion(power, number);
return sum;
//return bit * pow(2, power) + DecimalConversion(power, number);
}
int main(){
int power = 0;
int number = 0;
cout << "Enter binary number: " << endl;
cin >> number;
cout << "Number is: " << DecimalConversion(power, number);
system("PAUSE >> NULL");
return 0;
}
Is it possible to return value from DecimalCoonversion function by not using global variable? Can someone explain how, I tried next line of code but it does not work correctly:
return bit * pow(2, power) + DecimalConversion(power, number);
Can anyone explain where i am making mistake using previous line of code?
Thank You in advance
This adds sum as a parameter to your function, but makes it default to 0 if you don't provide it explictly. Power is also defaulted to 0, which saves you having to pass it into the function.
Since default parameters must be at the end of a function declarations and/or definitions parameter list, I had to move power across to achieve this.
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
int DecimalConversion (int number, int power = 0, int sum = 0) // changes here
{
if (number == 0)
{
return sum;
}
int bit = number % 10;
sum = sum + bit * pow(2, power);
number /= 10;
power++;
return DecimalConversion(number, power, sum); // changes here
}
int main(){
int number = 0;
cout << "Enter binary number: " << endl;
cin >> number;
cout << "Number is: " << DecimalConversion(number);
system("PAUSE >> NULL");
return 0;
}
Please note I didn't check this actually converts binary to decimal correctly, just that the recursion works.
You can call this function like so:
DecimalConversion(number);
This:
int DecimalConversion(int power, int number){
if (number == 0)
return 0;
else
return (number % 10)*pow(2, power) + dc(power+1, number/10);
}
or
int DecimalConversion(int power, int number){
return number?(number % 10)*pow(2, power) + dc(power+1, number/10):0;
}