How to display the values of a class? - c++

I am almost new in c++. I have created a class of a student. First of all, when i returned the media of the marks, it isn't a float value. For example: if I enter 5 and 10, it returns 7 instead of 7.5.
Secondly, when I want to display the name and media with the function disp(), it doesn't work.
Could anyone help a bit?
Thanks
#include <iostream>
using namespace std;
class student{
public:
string name;
int mark1, mark2;
float calc_media(){
float media = (mark1 + mark2)/2;
return media;
}
void disp(){
cout << "Student:" << name << endl;
cout << "media:"<< calc_media() << endl;
}
};
int main (){
student peter;
cout <<"name:" ;
cin>>peter.name;
cout <<"mark1:" ;
cin>>peter.mark1;
cout <<"mark2:" ;
cin>>peter.mark2;
cout <<"ALL:" << peter.disp();
return 0;
}

In this expression:
(mark1 + mark2) / 2;
you are doing integer division, since both the variables and the literal are int types. You could simply do:
(mark1 + mark2) / 2.0;
instead, to get floating point division.
To get disp to work, note that it doesn't return anything, so you need to simply call it like this:
peter.disp();
and not pass the result of this function to cout.
Alternatively, instead of disp, you can overload the operator<< like this:
std::ostream& operator<<(student const &s, std::ostream &out)
{
out << "Student:" << name << endl;
out << "media:"<< calc_media() << endl;
return out;
}
and then use it like this:
cout << peter;

Here what you are doing is called integer division, both variables mark1 and mark2 are integers and so is 2 thus, it will provide you an integer.
float calc_media(){
float media = (mark1 + mark2)/2;
Try replacing 2 with 2.0 to achieve floating point division.
float media = (mark1 + mark2)/2.0;
And as your disp function is not returning something you need not to cout it. You can do this,
cout <<"ALL:";
peter.disp();

Related

Why am i getting numbers in scientific form in simple calculations? [duplicate]

This question already has answers here:
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 1 year ago.
Background: So I basically googled projects for beginners for C++ and one recommendation was currency converter. So I decided to do this, at first I tried to do it by creating a class, objects etc but I got lost with constructors and header files etc but that's a story for another day. I am very new to programming and this is my first "project".
So I decided to go the simple route and did this:
#include <iostream>
int main(){
double euro;
//creating all the variables and conversions
double eur2dol = euro * 1.13;
double eur2pound = euro * 0.84;
double eur2rup = euro * 84.49;
double eur2yuan = euro * 7.2322769;
double eur2btc = euro * 0.0000237;
double eur2eth = euro * 0.00029956;
// creating an array with the name of the currency i am converting to
std::string curname[6] = { " Dollars\n", " Pounds\n", " Rupees\n", " Yuan\n", " Bitcoin\n", " Etherium\n"};
// creating an array with the conversions i want to do
double currencies[6] = { eur2dol, eur2pound, eur2rup, eur2yuan, eur2btc, eur2eth };
//accepting input from the user
std::cout << "Amount in euros: " << std::endl;
std::cin >> euro;
// for loop to loop through every item in the currencies array and the corresponding name of the currency from the curname array
for(int i = 0; i < 5; i++){
std::cout << euro << " Euro is " << currencies[i] << curname[i];
};
return 0;
}
Now, I know there is no point in doing this other than practicing because the values constantly change but I am getting the same result no matter the value I type in and in scientific form.
How can I fix it so i get the correct result and what is the problem?
A typical case of uninitialized variable. Here you are operating on euro variable before asking(cin) value for it, The correct implementation would be something like:
#include <iostream>
int main()
{
double euro = 0; //always put some values beforehand
//accepting input from the user
std::cout << "Amount in euros: " << std::endl;
std::cin >> euro;
//creating all the variables and conversions
double eur2dol = euro * 1.13;
double eur2pound = euro * 0.84;
double eur2rup = euro * 84.49;
double eur2yuan = euro * 7.2322769;
double eur2btc = euro * 0.0000237;
double eur2eth = euro * 0.00029956;
// creating an array with the name of the currency i am converting to
std::string curname[6] = { " Dollars\n", " Pounds\n", " Rupees\n", " Yuan\n", " Bitcoin\n", " Etherium\n"};
// creating an array with the conversions i want to do
double currencies[6] = { eur2dol, eur2pound, eur2rup, eur2yuan, eur2btc, eur2eth };
// for loop to loop through every item in the currencies array and the corresponding name of the currency from the curname array
for(int i = 0; i < 5; i++){
std::cout << euro << " Euro is " << currencies[i] << curname[i];
};
return 0;
}
Note: Uninitiazed variable is a bad practice. If you initialized the variable like double euro = 0; earlier, it will alteast not return arbitrary values even for the wrong code.
You can format your floating-point values with std::fixed and std::setprecision.
Apart from that:
Make sure you don't use euro before reading it.
Try and declare the variables as close to the place where you first use them as possible.
currencies array would probably better be called conversion_rates or something like that.
[Demo]
#include <iomanip> // setprecision
#include <ios> // fixed
#include <iostream>
int main() {
// creating all the variables and conversions
double eur2dol = 1.13;
double eur2pound = 0.84;
double eur2rup = 84.49;
double eur2yuan = 7.2322769;
double eur2btc = 0.0000237;
double eur2eth = 0.00029956;
// creating an array with the name of the currency i am converting to
std::string currency_name[6] = { "Dollar", "Pound", "Rupee", "Yuan", "Bitcoin", "Etherium" };
// creating an array with the conversions i want to do
double conversion_rates[6] = { eur2dol, eur2pound, eur2rup, eur2yuan, eur2btc, eur2eth };
// accepting input from the user
std::cout << "Amount in euros: " << std::endl;
double euro{};
std::cin >> euro;
// for loop to loop through every item in the currencies array and
// the corresponding name of the currency from the curname array
for (int i = 0; i < 6; i++) {
std::cout << std::fixed << std::setprecision(2) << euro << " Euro is "
<< std::setprecision(5) << euro * conversion_rates[i] << " " << currency_name[i] << "\n";
};
return 0;
}
You could as well slightly improve your solution and get started with concepts such as structs and STL containers just by:
defining a Currency struct, where you hold the the currency name and rate conversion from euros,
using a constant vector of currencies,
walking the vector with a range for loop.
[Demo]
#include <iomanip> // setprecision
#include <ios> // fixed
#include <iostream> // cout
#include <string>
#include <vector>
struct Currency
{
std::string name{};
double from_euro_rate{};
};
int main() {
const std::vector<Currency> currencies{
{"Dollar", 1.13},
{"Pound", 0.84},
{"Rupee", 84.49},
{"Yuan", 7.2322769},
{"Bitcoin", 0.0000237},
{"Etherium", 0.00029956}
};
// accepting input from the user
std::cout << "Amount in euros: ";
double euro{};
std::cin >> euro;
std::cout << euro << "\n\n";
// for loop to loop through every item in the currencies array and
// the corresponding name of the currency from the curname array
for (auto& currency : currencies) {
std::cout << std::fixed << std::setprecision(2) << euro << " Euro is "
<< std::setprecision(5) << euro * currency.from_euro_rate << " " << currency.name << "\n";
};
}

Cpp code equation returning the same value regardless of input

I am trying to write a wind chill calculator that works with temp. and wind speed values from user input. I have never used the pow() function before and I'm not sure if I am using it properly. My code is this:
#include <iostream>
#include <cmath>
using namespace std;
float windChillCalculator(float T, float V)
{
float wind_chill;
wind_chill = (35.74 + (0.6215 * T) - (35.75 * (pow(V, 0.16)))
+ ((0.4275 * T) * (pow(V, 0.16))));
return wind_chill;
}
int main()
{
float T;
float V;
cout << "Enter temperature (F): " << endl;
cin >> T;
cout << "Enter wind speed (mph): " << endl;
cin >> V;
float wind_chill;
windChillCalculator(T, V);
cout << endl << "Wind chill is " << wind_chill << endl;
}
Regardless of input it returns 4.59e-41. Please help me figure out why..
Thanks.
The problem here is probably that you are using two variables, both named wind_chill. First definition of wind_chill is in windChillCalculator function. This is local variable to function. Code outside of the function cannot see this variable (out of scope). Then windChill is defined out of the function, but is never asigned to.
Change line windChillCalculator (T, V); to windChill = windChillCalculator (T, V);
you should put in main :
float wind_chill = windChillCalculator(T, V);

Conversion Fahrenheit to Celsius using class c

Hello everyone I'm having a problem. I'm fairly new and been stuck trying to solve it.
When I run it the first part where it prints 0 for the Fahrenheit to Celsius is correct but once I input a number it just prints the number I input. I know it probably a simple answer but thank you for your time.
#include <iostream>
using namespace std;
class Temp
{
public:
Temp(); //CONSTRUCTOR: Sets private variable for Fahrenheit to 32
void InputF(float F); //Initialize Fahrenheit temperature to F
void Celsius(); //PRINTS the Celsius temperature corresponding to
// the private Fahrenheit equivalent temperature
void ChangeBy(float D); //Changes the private Fahrenheit temperature
// by D degrees.
float Fahrenheit(); // returns the value of the private Fahrenheit temp
private:
float Fah; //Fahrenheit Temperature
};
int main() {
float FF;
Temp T; // Temperature Object
T.Celsius();
cout << endl; //Note that the value will be 0 since the private variable is 32.
cout << "Input a Fahrenheit temp: ";
cin >> FF;
T.InputF(FF);
cout << T.Fahrenheit() << endl;;
T.ChangeBy(34);
cout << T.Fahrenheit() << endl;
system("Pause");
return 0;
}
Temp::Temp() {
Fah = 32;
}
void Temp::InputF(float F) {
Fah = F;
}
void Temp::Celsius() {
cout << Fah;
}
void Temp::ChangeBy(float D) {
Fah = (5.0 / 9) * (Fah - 32);
}
float Temp::Fahrenheit() {
return Fah;
}
So, one issue:
void Temp::ChangeBy(float D)
{
Fah = (5.0/9)* (Fah - 32);
}
This method does not do what you say it does in the class declaration; your comment says that it updates Fah by the number of Fahrenheit degrees passed to it.
If I may suggest the following changes:
First, have ChangeBy simply add the input value to Fah:void Temp::ChangeBy( float D )
{
Fah += D;
}
Second, have the Celcius method do the conversion and return the converted value:float Temp::Celcius()
{
return (5.0/9.0) * (Fah - 32.0);
}
Finally, in your main function, write the output of Temp::Celcius() to the output stream:std::cout << T.Celcius() << std::endl;
EDIT
I took the liberty of rewriting your code to show what I mean; there isn't enough space in a single comment to really get the point across:
#include <iostream>
using namespace std;
class Temp
{
public:
Temp( float f = 32.0 ); // slight change here
void InputF(float F);
float Celsius() const; // note return type, addition of const
void ChangeBy(float D);
float Fahrenheit() const; // note addition of const
private:
float Fah;
};
int main() {
float FF;
Temp T;
cout << T.Celsius(); // Note that we output the result of Celsius in
// exactly the same manner that we do for
// Fahrenheit below.
cout << endl;
cout << "Input a Fahrenheit temp: ";
cin >> FF;
T.InputF(FF);
cout << T.Fahrenheit() << endl;
T.ChangeBy(34);
cout << T.Fahrenheit() << endl;
return 0;
}
/**
* Slight change here; we're using a member initializer, rather than
* assigning Fah in the body of the constructor. For a simple class
* like this it doesn't matter, but when you start getting into derived
* and virtual classes, using this method will make sure things get
* initialized in the right places and in the right order.
*/
Temp::Temp( float f ) : Fah(f) {
}
void Temp::InputF(float F) {
Fah = F;
}
float Temp::Celsius() const {
return (5.0f / 9.0f) * ( Fah - 32.0f ); // use f suffix for float constants
}
void Temp::ChangeBy(float D) {
Fah += D; // Update the value of Fah by the input value; the code you
// posted isn't using the value of D to update Fah, it was
// simply converting Fah to Celsius.
}
float Temp::Fahrenheit() const {
return Fah;
}
This code builds and runs on a Linux system using g++ with the -pedantic -Wall -Werror flags.
So, I've changed the return type of Celsius from void to float; instead of having Celsius print the value, it simply returns the value to main. This way Celsius doesn't have to worry about where the output gets written (what if you wanted to write to a file instead of cout, for example), and its focus is now much narrower.
I also changed the ChangeBy function; in the implementation you pasted above, you aren't actually using the input parameter D to change the value of Fah; you're simply converting the value of Fah from Fahrenheit to Celcius.
Notice that I also added the trailing const qualifier to the Fahrenheit and Celsius methods. This indicates that these two methods will not attempt to update any data internal to Temp. It's a good idea to make such "query" methods const in this manner; it keeps you from writing code that makes changes where it shouldn't.

'SalesTaxPct' was not declared in this scope

I am new to C++. I am struggling with the pass by value thing, and no one can explain what I am doing wrong to me in a way I can understand. I know this is my fault, but Ii am asking for help with my code. HELP PLEASE!
#include <iostream>
using namespace std;
double getValues();
double getSalesTax(double SalesTaxPct);
double gettotal_price(double base, double opt);
void PrintFinal(double base,double opt,double SalesTaxPct);
// function to control all other functions
int main()
{
getValues();
getSalesTax(SalesTaxPct);
PrintFinal(base,pt,SalesTaxPct);
}
// function to calculate sales tax percent into decimal
double getSalesTax( double SalesTaxPct )
{
double SalesTax;
SalesTax = SalesTaxPct / 100;
return SalesTax;
}
// function to find total
double gettotal_price(double base, double opt, double SalesTax)
{
return = (base + opt) * (1 + SalesTax);
}
// function to show user all values input and also total
void PrintFinal(double base, double opt, double SalesTaxPct)
{
cout << "Base vehicle price: $" << base << endl;
cout << "Options Price: $" << opt << endl;
cout << "Sales tax pct: " << SalesTaxPct << "%" << endl;
cout << "Total vehicle price: $" << gettotal_price(double base, double opt, double SalesTax) << endl;
}
// function to get input values
void getValues()
{
double base, double opt, double SalesTaxPct;
cout << "Enter a base vehicle price: " << endl;
cin >> base;
cout << "Enter options price: " << endl;
cin >> opt;
cout << "Enter a sales tax percent: " << endl;
cin >> SalesTaxPct;
}
When you are in main, let's go over what the program sees:
int main()
{
getValues();
getSalesTax(SalesTaxPct);
PrintFinal(base,pt,SalesTaxPct);
}
The only variables that your program knows about at this point are: getValues(), getSalesTax(), gettotal_price(), and PrintFinal(). The warning is telling you that at this point of your program, SalesTaxPct was not declared yet, and looking at our list of variables / functions that the program knows about, we see that, indeed, SalesTaxPct is not on the list. Where do we expect the value of SalesTaxPct to come from?
It looks like that comes from the function getValues, and we are getting it from user input. However, any time that you have { ... }, the stuff inside the braces cannot be accessed outside. Therefore, SalesTaxPct is only "in scope" inside the function getValues. If you want it to be accessible outside of that function (which you do), you need to change things around a bit.
int main()
{
double base;
double opt;
double SalesTaxPct;
getValues(base, opt, SalesTaxPct);
getSalesTax(SalesTaxPct);
PrintFinal(base, opt, SalesTaxPct);
}
Now all of our variables still exist when we need them in main. However, there is still a problem here. We want the changes we pass into getValues to change the variables in main. This means we cannot pass "by value" because that will first make a copy, and then change those copies (not what we want). Instead, we need to say that the changes we make need to be returned from the function some how:
void getValues(double & base, double & opt, double & SalesTaxPct);
That little & there means that rather than making a copy and changing that copy, we are telling the function to operate on the variable we pass in directly. This is referred to as "pass by reference".
There are some similar problems in other parts of your code, but perhaps now you can figure out how to fix them.

My function will not return a value to the local variable in C++

I created a function to determine the value for cableBoxFeesTotal, I then have it return the value to the local variable cableBoxFeesTotal. When I try to use the value of cableBoxFeesTotal outside of the function, the value is 0.00, not the value that was returned from the function. I have been working on this for days, and cannot seem to figure out what I am doing wrong. Please advise me on how to fix this issue. Thanks!
I didn't want to post the entire code..it is homework, but I did add the two sections below.
#include <iostream>
#include <string>
#include <cctype>
#include <iomanip>
#include <cmath>
using namespace std;
const double BASIC_CABLE = 43.00;
const double PREMIUM_CABLE = 58.00;
const double BASIC_BOX = 7.50;
const double PREMIUM_BOX = 11.25;
const double PREMIUM_CHANNEL_FEE = 9.99;
const double EMPLOYEE_DISCOUNT_AMOUNT = .14;
double feeFunction (int cableBoxes, double serviceLevel, double cableBoxFeesTotal, double BASIC_BOX, double PREMIUM_BOX, char B, char P)
{
if (cableBoxes > 2 && serviceLevel == 'B')
{
cableBoxFeesTotal = ((cableBoxes - 2) * BASIC_BOX);
cout << "Cable Box Fees: " << setw(15) << cableBoxFeesTotal << endl;
}
else if (cableBoxes > 2 && serviceLevel == 'P')
{
cableBoxFeesTotal = ((cableBoxes - 2) * PREMIUM_BOX);
cout << "Cable Box Fees: " << setw(15) << cableBoxFeesTotal << endl;
}
return (cableBoxFeesTotal);
}
int main()
{
string employee;
bool hasPremium;
char H;
char B;
char P;
char premiumChannel;
char serviceLevel;
int cableBoxes = 0 ;
double customerID;
double monthlyRateTotal = 0.00;
double cableBoxFeesTotal = 0.00;
double premiumChannelTotal = 0.00;
double subtotal = 0.00;`enter code here`
double employeeDiscount = 0.00;
double total = 0.00;
feeFunction (cableBoxes, serviceLevel, cableBoxFeesTotal, BASIC_BOX, PREMIUM_BOX, B, P);
cout << cableBoxFeesTotal << endl;
if (hasPremium == true)
{
subtotal = (cableBoxFeesTotal + monthlyRateTotal + PREMIUM_CHANNEL_FEE);
cout << "Subtotal:" << setw(15) << subtotal << endl;
}
else if (hasPremium == false)
{
subtotal = (monthlyRateTotal + cableBoxFeesTotal);
cout << "Subtotal:" << setw(15) << subtotal << endl;
}
}
You don't actually call the function anywhere, so it's unclear what you think is supposed to happen. Furthermore, note that the parameter cableBoxFeesTotal in the method and the local variable cableBoxFeesTotal in main() are two separate unrelated variables. You need to do something like this in main():
cableBoxFeesTotal = feeFunction (1, 1.0, 0, 1.0, 1.0, 'b', 'p');
to call it (where I've just made up values for the parameters, since I don't know what you intend.) Looking over the code, I see that the names of most of the parameters to the function duplicate the names of global or local variables elsewhere; I suspect you just don't really know how parameters work yet, is that right? IN which case, you need to go back to your textbook and do some more reading.
if you were to call your function feeFunction with the parameters you defined in main cableBoxes is ALWAYS < 2. Since the computation part of your function checks to see that cableBoxes > 2 it ALWAYS skips the computations and returns the value originally assigned to cableBoxFeesTotal namely 0.00
Furthermore, you define your globals as const, so even if the computations were happening in the function, it wouldn't change the global values you defined.
It is still unclear what you are trying to compute etc... but with some more information I can try to advise you on what to do to fix your code. For now suffice it to say make sure your conditions in the function are checking things appropriately.
could you show me codes for the int main() and in this code, I dont see where you use the function feeFunction(). If I still remember, to return a value, we just use return cableBoxFeesTotal; . Let me re-check the C++ syntax first and I'll come back with a more concrete answer to solve this. In meanwhile, please dump full codes for this one.
First your function usage is wrong. When you return a value through function, when call - you need to put the value in variable.
make it as:
double totalFeeFunction = feeFunction (cableBoxes, serviceLevel, cableBoxFeesTotal, BASIC_BOX, PREMIUM_BOX, B, P);
Only then you could use it with the value return to your main is in totalFeeFunction