C++ expression must be an lvalue or a function designator - c++

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... *

Related

Multiplying a digit of a number with its current position and then add it with the others using recursion

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;
}

Ceil function in finding median

I am learning C++ using "Programming Principles and Practice using C++" by Bjarne Stroustroup. In the following question of finding median, I have problem with the ceil function. Say, for example, I input 14 entries then value of a should be 6 and value of b should be 7. But the value of b is coming out 6.
#include "std_lib_facilities.h"
using namespace std;
int main()
{ vector<double> temps;
for(double temp;cin>>temp;)
{temps.push_back(temp);
}
sort(temps);
for(double temp : temps)
cout << temp << " " ;
int size = temps.size();
if(size%2 == 0)
{ int a,b,c;
a = temps[floor((size + 1)/2) - 1]; cout << a;
**b = temps[ceil((size + 1)/2) - 1 ]; cout << b;**
cout<<"Median temperature:"<<(a+b)/2<<'\n';
}
else
cout<<"Median temperature:"<<temps[((size + 1)/2) - 1]<<'\n';
return 0;
}
std_lib_facilties.h link
since size is an int, (size+1)/2 will perform an integer division, and will return only the whole part of the division. Applying ceil to it, as you saw, is pointless.
You could work around it by defining size as a double, or casting it inline:
**b = temps[ceil((((double)size) + 1)/2) - 1 ];

What does accumulate do in C++?

i'm new to c++, recently I discovered a function called accumulate(). I searched over internet about what it is, and read the C++ Reference tutorial, but couldn't understand what it does
#include <iostream>
#include <numeric>
using namespace std;
int main ()
{
int init = 100;
int numbers[] = {10,20,30};
cout << accumulate(numbers,numbers+3,init) << "\n";
}
Why is the output of the above program 160? I would like to know what the function does and how it works. Any types help appreciated.
accumulate without a special function takes two iterators and returns the sum, your init specifies the starting variable. It's like fold or a functional "reduce." The code above gives 160 because it's calculating
100 + 10 + 20 + 30
numbers will be a pointer to the beginning of the array, numbers+3 is "one-past-end" a typical c++ iterator idiom. It might be clearer if it was written out as
#include <iostream>
#include <iterator>
#include <numeric>
int main ()
{
int init = 100;
int numbers[] = {10,20,30};
std::cout << std::accumulate(std::begin(numbers), std::end(numbers), init) << "\n";
}
It should be clearer in this example what the range is, the beginning of numbers to the end of numbers. The init variable becomes vital in different cases such as an empty sequence.
You could also specify a different function to use instead of addition, the following will result in init * 10 * 20 * 30
int mul(int a, int b) {
return a * b;
}
int main ()
{
int init = 100;
int numbers[] = {10,20,30};
std::cout << std::accumulate(std::begin(numbers), std::end(numbers), 1, mul) << "\n";
}
Though such simple functions are often written as lambdas
We can represent the function like this :
accumulate(first, last, init)
Here accumulate() function sums up all the values in the range [first,last) that is between first and (last-1) index
And here init is the initial value of the sum.
The function is similar to the following c++ code :
#include <iostream>
#include <numeric>
using namespace std;
int main ()
{
int init = 100;
int numbers[] = {10,20,30};
int first = 0, last = 3;
int sum = init;
for(int i = first ;i < last ;i++)
sum = sum + numbers[i];
cout << sum << "\n";
}
So in your example : init + number[0] + number[1] + number[2] = 100 + 10 + 20 +30 = 160
One more thing :
accumulate(numbers, numbers + 3, init)
You may ask, why we are passing numbers in the first parameter rather than 0 ?
The answer is :
Here accumulate() function does not know which array you are willing to sum up.
So you need to inform the starting address that is address of numbers[0] to the function.
And if you want to sum up element between x position to y-1 position. You have to write this :
accumulate(numbers + x, numbers + y, init)
std::accumulate
is what it's name suggests. It just sums up the whole sequence. In addition you can provide an initial value. In your case initial value is 100.
Well, if you read the documentation it says
Returns the result of accumulating all the values in the range
[first,last) to init.
So...
numbers = 10 + 20 + 30 = 60 , init = 100 => 100+60 => 160.
std::accumulate is taking as first iterator, number, and last iterator number+3.

Nested For Loop (C++) Not Working Properly

I am working on some programming homework and I am trying to use a for-loop in order to facilitate the process of the coding. Here is the loop:
#ifndef DIVSALES_H
#define DIVSALES_H
class DivSales
{
public:
DivSales(){ quarterSales[4] = {0}; };
double getTotalSales() { return totalSales;}
static void setTotalSales(double);
static void addTotalSales(double);
double getQuarterSales(int numQuarter) {return quarterSales[numQuarter];}
void setQuarterSales(int numQuarter, double numAmount) { quarterSales[numQuarter] = numAmount;}
private:
static double totalSales;
double quarterSales[];
};
double DivSales::totalSales = 0;
void DivSales::setTotalSales(double totalAmount) {totalSales = totalAmount; }
void DivSales::addTotalSales(double addAmount) {totalSales += addAmount; }
#endif // DIVSALES_H
#include <iostream>
#include "DivSales.h"
using namespace std;
int main()
{
const int NUMDIVS = 6;
const int NUMQUARTERS = 4;
double amount = 0;
DivSales divs[NUMDIVS];
for(int division = 0; division < NUMDIVS; division++)
{
cout << "Division " << (division + 1) << endl;
for(int quarter = 0; quarter < NUMQUARTERS; quarter++)
{
cout << "Quarter " << (quarter + 1) << ": ";
cin >> amount;
divs[division].setQuarterSales(quarter, amount);
DivSales::addTotalSales(amount);
}
}
return 0;
}
Example of the output:
Division 1
Quarter 1: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2:
What I am trying to do is make it so that when I have input the numbers for the 4 quarters of a division, that it will move onto the next division. However, after 4 inputs it is not incrementing the division variable of the for-loop instead it continues asking for more inputs. What is going on?
I have found what's causing that problem, it is in the file DivSales.h:
Change this line:
double quarterSales[];
For this line:
double quarterSales[4];
The problem was that you were not allocating memory for an array of 4 elements. To initialize it, change your constructor to this:
DivSales():quarterSales({0}){ };
You should also move the following line to DivSales.cpp, because otherwise I was getting a multiple definition error:
double DivSales::totalSales = 0;
Here:
divs[division].setTotalSales(amount);
you probably want:
divs[division].addTotalSales(amount);
But that is not what is causing your problem. Which I cannot reproduce.

Getting random numbers to stay the same from function to function

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;
}