Why is my program giving weird results? - c++

The following snippets are the header file and the actual main() function. I am using Visual Studio 2017 with Windows 10.
.h
#ifndef SALES_DATA_H
#define SALES_DATA_H
#include <iostream>
using namespace std;
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
};
#endif
.cpp
#include <iostream>
#include "Sales_data.h"
using namespace std;
int main()
{
Sales_data item1;
cout << "Enter rate and amount" << endl;
cin >> item1.rate >> item1.amount;
cout << item1.price << endl;
cin.get();
cin.get();
return 0;
}
It keeps showing this as the output: "687194768".
I also tried initializing the variables but it does not seem to work.

What you probably want is:
struct Sales_data
{
int amount = 0;
int rate = 0;
int price() const { return amount * rate; }
};
And then
std::in >> item1.rate >> item1.amount;
std::cout << item1.price() << std::endl;

Price here is being calculated only at initialisation time to get its initial value, however since amount and rate have not been initialised yet, the result is undefined.
It is not a function.
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
};
You most likely wanted a function, e.g.:
struct Sales_data
{
int amount;
int rate;
int calcPrice()
{
return = amount * rate;
}
};
std::cout << item1.calcPrice() << std::endl;
Or you would have to refactor to initialise amount and rate to make use of such syntax, e.g. with a constructor.
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
Sales_data(int amount, int rate) : amount(amount), rate(rate) {}
};
Sales_data x(10, 5);
//x.price == 50

the reason the code is printing that is because you are calculating that price with uninitialized variables...
define a function in the struct and call it after the input is given
void calculatePrice() {
price = amount * rate;
}
cin >> item1.rate >> item1.amount;
item1.calculatePrice();
cout << item1.price << endl;

As others have commented, your definition for Sales_data uses amount or rate before they were ever initialised. This is undefined behaviour, and your compiler is more or less free to do whatever it pleases with this.
Many compilers will initialise variables with some sort of recognisable guard value (a popular choice is 0xDEADBEEF) as a way to make it quite obvious when a value is uninitialised when looking at it with a debugger. In this case, it looks like your compiler uses 0xCCCCCCCC as that guard value:
(lldb) p (int) 0xcccccccc * (int) 0xcccccccc
(int) $2 = 687194768

Related

C++ class using a variable from private class

I am trying to use a variable from the private class and both add and subtract from it at different times, first add 5 to it 5 times then subtract 5 from it 5 times and each time i have to display its value. Currently i have:
#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
class car {
private:
int year;
string make;
int speed;
public:
void StoreInfo(int y, string m, int s);
int getSpeed() { return speed; }
int accelerate() { speed += 5; }
int brake() { speed -= 5; }
};
void car::StoreInfo(int y, string m, int s) {
year = y;
make = m;
speed = s;
}
car fillFields() {
car Filler;
int year; // Local variables to hold user input
string make;
int speed = 0;
// Get the data from the user
cout << "Enter year: ";
cin >> year;
cout << "Enter make: ";
cin.get(); // Move past the '\n' left in the
// input buffer by the last input
getline(cin, make);
cout << "The current speed is " << speed << endl;
Filler.StoreInfo(year, make, speed);
return Filler;
}
int main() {
car numbers = fillFields();
car::accelerate();
return 0;
}
This code accepts the input but does not work after that i realize that the car::accelerate() line in the main is incorrect now but how would i use it correctly?
First accelerate and brake do not return any value so you can make them void
void accelerate() { speed += 5; }
void brake() { speed -= 5; }
accelerate is non-static member function and needs an object so you need to call it like:
numbers.accelerate();
And for example change your main function like this to accerelate once and then brake and see the speed:
int main() {
car numbers = fillFields();
numbers.accelerate(); // +5
cout << "The current speed is " << numbers.getSpeed() << endl;
numbers.brake(); // -5
cout << "The current speed is " << numbers.getSpeed() << endl;
return 0;
}
Outputs:
Enter year: Enter make: The current speed is 0
The current speed is 5
The current speed is 0
Demo
You can replace car::StoreInfo with a constructor, because it does what the constructors are meant for. And don't forget to initialize your variables.
numbers.accelerate();
You are not using any static data. You could rename numbers variable if you want.

Having issues with void function

I'm trying to the program to display the bonus, but the programs renders an answer to 0. I am extremely new to c++ so any guidance would be greatly appreciated.
Here's the code:
#include <iostream>
#include <iomanip>
using namespace std;
//function prototypes
void enterItems(double, double);
void calcAndDisplayBonus(double &salesAmt, double &rate);
int main()
{
//declare variables
double sales = 0.0;
double bonusRate = 0.0;
//enter input values
enterItems(sales, bonusRate);
//calculate and display bonus
cout << fixed << setprecision(2);
calcAndDisplayBonus(sales, bonusRate);
system("pause");
return 0;
} //end of main function
//*****function definitions*****
void enterItems(double salesAmt, double rate)
{
cout << "Enter sales: ";
cin >> salesAmt;
cout << "Enter bonus rate (in decimal form): ";
cin >> rate;
} //end of enterItems function
void calcAndDisplayBonus(double &salesAmt, double &rate)
{
cout << "Bonus: $" << salesAmt * rate << endl;
} //end of calcAndDisplayBonus function
When you call enterItems, you are passing parameters by copy. This means that your changes won't affect the variables available in the scope of the caller.
To solve it, you can either pass a couple of references or pointers, as well as rely on a pair returned from the function as a result, and so on.
As an example, by writing:
void enterItems(double &salesAmt, double &rate)
You'll actually solve the problem above mentioned.
Another valid prototype is:
void enterItems(double *salesAmt, double *rate)
Even though this one asks for a small set of changes all around your code (the example, of course).
There is a plenty of possible solutions, hoping these ones will give you an idea of what's wrong.
Your function
void enterItems(double salesAmt, double rate)
is taking two double-parameters by value, this means, your changes you do inside the function will not be visible from the outside. You could take the doubles by reference:
void enterItems(double &salesAmt, double &rate)
but i'd prefer to return the values, but since you can only return a single value you'd need two functions:
double enterSales()
{
double tmp;
cout << "Enter sales: ";
cin >> tmp;
return tmp;
}
double enterBonus()
{
double tmp;
cout << "Enter bonus rate (in decimal form): ";
cin >> tmp;
return tmp;
}
//in your main:
double sales = enterSales();
double bonusRate = enterBonus();

Passing Variables Through Functions in C++

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)
Use returned value or pass parameter by reference or pointer.
1.
int result = numRobots(number);
2.
int numRobots(int& number) {.....}
You need to pass the variables by reference:
int cost = 0;
int number = 0;
price(cost);
numRobots(number);
void price(int& cost)
{
....
}
void numRobots(int& number)
{
....
}
Note the void return type in this case!
Alternatively, you can utilize the return value:
int cost = price(cost);
int number = numRobots(number);
But this method doesn't make much sense because the variable passed as parameter to methods is the same as the one in which the return value is stored!

Error 1 error C4700: uninitialized local variable 'rate' and 'hours' in C++

I am a beginner to programming. I'm writing a C++ program that a user will their pay rate and the hours worked, and then calculate the pay and hours worked then display it. I finish the program the there are two errors that I tried to fix but I still can't figure out to fix it. The errors and my code is below. Can someone help me and tell me how to fix? I'm using MSVS Express 2013.
Errors:
Error 1 error C4700: uninitialized local variable 'hours'
Error 2 error C4700: uninitialized local variable 'rate'
(It is erroring on displayWeekly(rate, hours);)
My Code:
#include "stdafx.h"
#include<iostream>
using namespace std;
void displayWeekly(double rate, int hours);
double getRate();
int getHours();
int main()
{
double rate;
int hours;
displayWeekly(rate, hours);
double getRate();
int getHours();
rate = getRate();
hours = getHours();
system("pause");
return 0;
}
void displayWeekly(double rate, int hours)
{
double weekPay;
weekPay = rate * hours;
cout << "Weekly pay is " << weekPay << endl;
}
double getRate()
{
double rate;
cout << "Enter your Hourly rate in the Dollars and Cents = ";
cin >> rate;
return rate;
}
int getHours()
{
int time;
cout << "Please Enter in the Hours you worked" << endl;
cout << "You must Enter a whole Number = ";
cin >> time;
return time;
}
Your new main should look something like this:
int main()
{
double rate;
int hours;
//double getRate(); --> where do you think the return value is stored to?
//int getHours(); -->
rate = getRate();
hours = getHours();
displayWeekly(rate, hours); // --> has to go after you put values to rate & hours
system("pause");
return 0;
}
You pass uninitialized variables to displayWeekly ,multiply them and print them which causes the error. Instead,call that function after you call getHours and getRate so that they get initialized.
Also
double getRate();
int getHours();
In main are unecessary.Remove them.
Here the main mistake that you have done is ignoring the order (flow ) of your code .
int main()
{
double rate;
int hours;
displayWeekly(rate, hours);//-> this is the func call that lead to error,cozz the arguments rate,hours are not still initialized .You calculated them after the function call.
double getRate();
int getHours();
rate = getRate();
hours = getHours();
//->it helps if you call display func here.
system("pause");
return 0;
}

C++ - Name/Access Class with char variable

I'm relative new to C++ and I'm sure there is probably plenty on information on here. Unfortunately, I don't seem to understand it.
I have a class called Account with variables called Number and Balance. The Member Name is given by the User through cin and represent an Account Number. I was able to dynamically create an object through cin. and give their variables a value through cin. However, I'm not able to give the variables a value or ask for the values in the class through cin.
I have been looking for hours and just cannot figure it out. Any help is appreciated. Thanks guys.
Here is my code:
class Account {
public:
int Number;
int Balance;
};
int main() {
int Nmbr;
int Bal;
cin >> Nmbr;
cin >> Bal;
Account Nmbr; // create the object
Nmbr.Number = Nmbr; // add the cin input 'Nmbr' to the variable Number - FALSE
Nmbr.Balance = Bal; // add the cin input 'Bal' to the variable Balance - FALSE
cout << Nmbr.Number << endl; // display Account.Number - FALSE
cout << Nmbr.Balance << endl; //display Account.balance - FALSE
}
Ok I think something like this is what you are after:
account.h:
class Account
{
public:
Account();
Account(int number);
int Number;
int Balance;
};
account.cpp:
#include "account.h"
Account::Account() {}
Account::Account(int number) {
this->Number = number;
}
So then in main you would do something like:
#include <iostream>
#include "account.h"
#include <vector>
const size_t MAXNUM = 5;
int main()
{
std::vector<Account*> allAccounts;
for (int accntNumber = 0; accntNumber < MAXNUM; accntNumber++) {
Account* account = new Account(accntNumber);
allAccounts.push_back(account);
}
// Then later do other stuff:
for (int accntNumber = 0; accntNumber < MAXNUM; accntNumber++) {
Account* checkAccount = allAccounts.at(accntNumber);
std::cout << "Account # = " << checkAccount->Number << std::endl;
}
return 0;
}
Edit: added an account class with a class creator based on the account number.