10

Passing variables via functions in C ++

 2 years ago
source link: https://www.codesd.com/item/passing-variables-via-functions-in-c.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Passing variables via functions in C ++

advertisements

So I'm trying to write a basic program in C++ to get the cost of something, the quantity, and calculate the total/subtotal, in three different functions, then display it in main().

Problem is, the variables aren't making it out of the function and I don't know why. I've put output statements inside the functions themselves to check, and the problem only seems to be when I'm trying to pull them out of said functions.

#include <iostream>

using namespace std;

int price(int cost)
{
cout << "What is the cost of the robot?" << endl;
cin >> cost;

if (cost < 1000) //validation
{
    cout << "Cost is too low. Setting to $1000." << endl;
    cost = 1000;
    return cost;
}

return cost;
}

int numRobots(int number)
{
cout << "How many robots are being ordered?" << endl;
cin >> number;

if (number < 50) //validation
{
    cout << "We only sell in quantities of 50 or more. Setting quantity to 50." << endl;
    number = 50;
    return number;
}

return number;
}

void grandTotal(int cost, int number, double &subtotal, double &total)
{
subtotal = (cost * number);
total = (subtotal * .07) + subtotal;
}

int main()
{
int cost = 0;
int number = 0;
double subtotal = 0;
double total = 0;

price(cost);`enter code here`
numRobots(number);
grandTotal(cost, number, subtotal, total);

cout << cost; //testing
cout << number; //outputs
cout << total; //of
cout << subtotal; //variables

system("pause");
return 0;


price(cost);

You are calling a function which returns an int, but you're not storing the int anywhere. You might want to go back to your text book and check the chapter on functions, and how they work. No offense but this is rather basic.

You're doing the same thing with numRobots.

Alternatively, you could pass the parameter by reference and modify it, but imo, that's less easy to understand.

tl;dr;

You should be doing int cost = price(); (there's no reason for the function to take an int as a parameter)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK