Variable Help Question

Pages: 12
The main part of the program will call a single function three times, passing in no data, but the function will prompt the user to enter a patient’s weight. It will then return this weight value to the main part of the program, placing it into three different variables there.

I need the input from the float getWeight() function and return it to the int main() function, putting the input into different variables as explained above. Thanks.

#include <iostream>
#include <string>

using namespace std;

float getWeight();
float averageWeight(float ,float ,float);


int main()
{


getWeight();
average=averageWeight();

cout << "The patient's average weight is: " << average << " lbs" << endl;

system ("pause");

return 0;
}

float getWeight()
{
float weightOne, weightTwo, weightThree;

cout << "Please enter a weight: ";
cin >> weightOne;
cout << "Please enter a weight: ";
cin >> weightTwo;
cout << "Please enter a weight: ";
cin >> weightThree;

return weightOne, weightTwo, weightThree;
}

float averageWeight(float weightOne,float weightTwo,float weightThree)
{
float average=0.00;

average=(weightOne+weightTwo+weightThree)/3.00;

return average;
}
Last edited on
Let's start with these observations:

getWeight();

That calls the function, which is supposed to return a float.

a float. Not 3 floats.

Yet, you're not taking the float it returns.

You are supposed to call getWeght() 3 times.

Each time it should ask for a weight and return it.

You retain those three waits as the return from the function, as in:

weightOne = getWeight();

....I'll let you do that 3 times.

The idea is that this two step process of printing out the question and getting the result is wrapped into one function call to getWeight();

Now, a hint as to what's next:

averageWeight takes 3 floats, but when you call it with:

averageWeight();

You are not providing any parameters.

Try figuring that out once you fix the first part, and it might start making sense before you ask the next questions.


Yes, also there is no need to include the string library, you don't use any strings in the program.
Hey, this is what I got now. When I run the program in the command prompt, it's giving me "Please enter a weight: " 9 times. It should be 3 times. What's the problem?

#include <iostream>
#include <string>

using namespace std;

float getWeight();
float averageWeight(float,float,float);


int main()
{
float weight1, weight2, weight3, average;


weight1=getWeight();
weight2=getWeight();
weight3=getWeight();


average=averageWeight(weight1, weight2, weight3);

cout << "The patient's average weight is: " << average << " lbs" << endl;

system ("pause");

return 0;
}

float getWeight()
{
float weightOne1=0.00;
float weightTwo2=0.00;
float weightThree3=0.00;

cout << "Please enter a weight: ";
cin >> weightOne1;
cout << "Please enter a weight: ";
cin >> weightTwo2;
cout << "Please enter a weight: ";
cin >> weightThree3;

return weightOne1, weightTwo2, weightThree3;
}

float averageWeight(float weightOne,float weightTwo,float weightThree)
{
float average=0.00;

average=(weightOne+weightTwo+weightThree)/3.00;

return average;
}

PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.


It's asking you three times because you're calling the function three times. Try this:
1
2
3
4
5
6
7
8
9
float getWeight ()
{
	float weight;

	cout << "Please enter a weight: ";
	cin >> weight;

	return weight;
}


That should take care of it. You can't return three different values from a function, as far as I know.
You can't return three different values from a function, as far as I know.


You could return an std::array, a struct, a std::tuple etc.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

float getWeight();
float averageWeight(float, float, float);

int main()
{
	const auto weight1 {getWeight()};
	const auto weight2 {getWeight()};
	const auto weight3 {getWeight()};

	const auto average {averageWeight(weight1, weight2, weight3)};

	cout << "The patient's average weight is: " << average << " lbs\n";
}

float getWeight()
{
	float weightOne1 {};

	cout << "Please enter a weight: ";
	cin >> weightOne1;

	return weightOne1;
}

float averageWeight(float weightOne, float weightTwo, float weightThree)
{
	return (weightOne + weightTwo + weightThree) / 3.00;
}

@seeplus
Yes, but with an array, struct, or tuple, you aren't saying something like
 
return first, second, third;

Instead, you're just returning
 
return structure; // or array, tuple, etc. 

So you can't return more than one thing from a function. The thing might contain an address to memory containing multiple values, but you aren't actually returning multiple values.

Note: I am not too familiar with tuples, so please feel free to correct me if I'm wrong about them.
You could do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <tuple>
#include <iostream>

auto myfunc(void)
{
	double d1 {34.56}, d2 {45.78}, d3 {76.78};

	return std::make_tuple(d1, d2, d3);
}

int main()
{
	auto [d1, d2, d3] {myfunc()};

	std::cout << d1 << ' ' << d2 << ' ' << d3 << '\n';
}


But yes, you only return one thing from a function.
Last edited on
I didn't know you could return a function from a function, but I will say it works! Although I have to set a -std=c++17 flag when I compile it.
Last edited on
What is being returned from the function is the results of the std::make_tuple function, not the function itself.

A not so subtle distinction.

Line 13 uses C++17's structured binding to "link" the 3 variables in main (d1, d2, d3) to the returning std::tuple's 3 values.
https://en.cppreference.com/w/cpp/language/structured_binding

Using auto as the type for the function return and the 3 variables in main lets a tuple be of different types and the compiler knows what to do. d1 is a double&&, d2 is a const char*&& string, d3 is an int&& (according to VS 2019 intellisense):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <tuple>
#include <iostream>

auto myfunc()
{
	return std::make_tuple(34.56, "Hello", 19);
}

int main()
{
	auto [d1, d2, d3] { myfunc() };

	std::cout << d1 << ' ' << d2 << ' ' << d3 << '\n';
}

34.56 Hello 19

I'm dumb, I didn't realize that. Yes, that would make sense. I don't think I've heard of "structured binding," but I will look into it, because it looks like a potentially useful tool for an idea I have.

Note: auto is a C++11 extension so I have to compile it with the -std=c++11 flag so it compiles.
Hello CornFlakes123,

Lets look at your second program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <limits>  // <--- Added.
#include <string>

using namespace std;  // <--- Best not to use.

double getWeight();
double averageWeight(double weightOne, double weightTwo, double weightThree);


int main()
{
    double weight1{}, weight2{}, weight3{}, average{};  // <--- Always initialize your variables.

    weight1 = getWeight();
    weight2 = getWeight();
    weight3 = getWeight();

    average = averageWeight(weight1, weight2, weight3);

    cout << "The patient's average weight is: " << average << " lbs" << endl;

    //system("pause");

    // A fair C++ replacement for "system("pause")". Or a way to pause the program.
    // The next line may not be needed. If you have to press enter to see the prompt it is not needed.
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
    std::cout << "\n\n Press Enter to continue: ";
    std::cin.get();

    return 0;  // <--- Not required, but makes a good break point.
}

double getWeight()
{
    double weightOne1 = 0.00;
    double weightTwo2 = 0.00;
    double weightThree3 = 0.00;

    cout << "Please enter a weight: ";
    cin >> weightOne1;

    cout << "Please enter a weight: ";
    cin >> weightTwo2;

    cout << "Please enter a weight: ";
    cin >> weightThree3;

    return weightOne1, weightTwo2, weightThree3;  // <--- Can return only 1 of the 3 and most likely returning the value of the last 1.
}

double averageWeight(const double weightOne, const double weightTwo, const double weightThree)  // <--- Made constant because they should not be changed.
{
    double average = 0.00;

    average = (weightOne + weightTwo + weightThree) / 3.00;

    return average;
}

Your code with some comments and changes.

Prefer to use "double" over "float".

You program is doing exactly what you told it to do.

When you say:

"Please enter a weight: " 9 times. It should be 3 times. What's the problem?


The program is doing what you told it to do and (9) times is expected.

A function should do 1 thing and do it well then return something if needed. Next a function can only return 1 thing. In your program that should be the weight that is entered. Asking for 3 weights and calling the function 3 times is where you (9) is coming from.

An alternative would be to pass the 3 variables by reference then you would not have to deal with a return value.

Compare your function call to what your function is doing. This may help
https://www.learncpp.com/cpp-tutorial/introduction-to-functions/

Also compare the "getWeight" function to the "averageWeight" function which is properly coded.

Your "getWeight" function is over done. It only needs to be asking for 1 weight and returning its value. That is why you have 3 function calls.

One last note: A prototype may only need the variable type, but copying the function definition with the variable names can help when writing a function call if your IDE supports this.

Andy
agent max wrote:
auto is a C++11 extension so I have to compile it with the -std=c++11 flag so it compiles.

Not 100% true. You need to compile as C++11 OR later. C++14, C++17, etc.

The code seeplus and I posted requires C++17 for the structured binding. If there wasn't structured binding C++11 would be acceptable. But compiling as C++14 (the default setting with Visual Studio 2019 at present) or C++17 will work as well.

So should whatever the C++20 standard is currently flagged as with your compiler if it has the support. VS: -std=latest, C::B: -std=2a.

There are very rare times when compiling certain code to a later standard CAN cause problems.

For example, std::random_shuffle. Deprecated in C++14, removed in C++17 (and later).
https://en.cppreference.com/w/cpp/algorithm/random_shuffle

std::shuffle is the replacement.

Most times compiling C++11 code against a later standard won't be a problem.

Unless I know I will be using C++20 features I default compile against C++17. When the compilers/IDEs I normally use are fully updated to C++20 I will set that as the default.
Oh, ok, that makes sense. Thanks, Furry Guy!

By the way, do you know of any functions or anything like that that are C++20 extensions? I just want to test the -std=2a flag and see if it works.

Thanks for all the help!
max
Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <vector>
#include <iostream>
#include <iterator>

int main()
{
	const std::vector vi {1, 2, 3};

	std::cout << "signed size: " << std::ssize(vi) << '\n';

	for (size_t i {}; const auto& v: vi)
		std::cout << i++ << ' ' << v << '\n';
}


Note no type specifier for vector, ssize() rather than size() and the initialiser within the range-for. This compiles and runs OK with VS2019.

Thanks, seeplus! I'll try it!

Edit:
Welp, I tried it, and it gave me these errors:

pr1.cc:9:39: error: no member named 'ssize' in namespace 'std'; did you mean 'size'?   
        std::cout << "signed size: " << std::ssize(vi) << '\n';
                                        ~~~~~^~~~~
                                             size

pr1.cc:11:32: error: variable declaration in condition must have an initializer
        for (size_t i {}; const auto& v: vi)
                                      ^

I guess my compiler only supports up to C++17.
Thanks!
max
Last edited on
C++ compiler support for C++20 features, and now C++2b (C++23 if/when finalized):
https://en.cppreference.com/w/cpp/compiler_support

Probably the easiest feature to check for is if char8_t is recognized as a valid type:
https://en.cppreference.com/w/cpp/language/types#char8_t
I guess my compiler only supports up to C++17.

What is your compiler/IDE, what is your OS?

A newer version may be available. VS 2019 has a rather largish update today. Currently installing it.
I don't use an IDE, mainly because 1: I don't have XCode, 2: I don't like Microsoft VS, 3: I don't want to install Dev-C++ or anything like that, and 4: they're really too much hassle for what I do.

I use the clang compiler in the Terminal application on my Mac for compiling, it works all right. Plus, it looks really cool when you put it in fullscreen mode, and it shows the code scrolling down, really impresses my friends at work.

My OS: macOS High Sierra, version 10.13.6

Compiler:
Apple LLVM version 10.0.0 (clang-1000.10.44.4)
Target: x86_64-apple-darwin17.7.0
Thread model: posix

Debugger:
lldb-1000.0.38.2
  Swift-4.2

Code Editor: Macromates' TextMate application (version 2.0.17)
I also use the vim text editor in Terminal for editing code sometimes.
Pages: 12