Conversion Fahrenheit to Celsius using class c - 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.

Related

why it does not return anything?

I'm doing a programming exercise about converting Fahrenheit to Celsius [C = 5/9 * (F-32)] with some conditions:
create a function toCelsiusByReference which takes a temperature by reference, and returns a bool so : bool toCelsiusByReference(float &temperature);
change the parameter from Fahrenheit to the equivalent Celsius
return true if the parameter was above freezing (>32 F), return false
I did 1 and 2 and I'm stuck with 3 which does not return me anything. I do not understand why?
I'm testing the value 60 F as temperature which should return me true since 60 F > 32 F.
Why my function bool toCelsiusByReference(float &temperature) does not return me anything
Here is the code :
#include <iostream>
#include <iomanip>
using namespace std;
bool toCelsiusByReference(float &temperature);
int main()
{
float temperature = 60;
toCelsiusByReference(temperature);
return 0;
}
bool toCelsiusByReference(float &temperature)
{
float celsius;
bool status;
// convert celsius to Fahrenheit
cout.setf(ios::fixed, ios::floatfield);
celsius = 5.00 / 9.00 * (temperature - 32);
// cout << "Degrees C : " << setprecision(2) << celsius << endl;
// check if temperature (fahrenheit) is freezing (<32) or not
if (temperature > 32)
{
status = true;
}
else
{
status = false;
}
return status;
}
In your case, it would appear that you are not storing what the function (toCelsiusByReference) returns: toCelsiusByReference(temperature);.
Now, from a coding perspective, I'd recommend some changes. Try to keep your methods as simple as possible. In your case, you are doing a temparature check in your conversion mechanism, which, at least in my opinion, shouldn't be there.
This also makes the name of the method a bit misleading, since true or false isn't what one would expect from a method called toCelsiusByReference.
So in short:
In your toCelsiusByReference method, return the equivalent value in degrees celcius.
In your main, add the logic for the freezing point temperature.
Basic knowledge: you need to use the returned value somehow.
...
if (toCelsiusByReference(temperature))
{
cout << "above 32°F\n";
}
else
{
cout << "below 32°F\n";
}
cout << "Converted temperature: " << temperature << " °C\n";
...
Short answer:
Store value returned from function
int main
{
...
bool b = toCelsiusByReference(...)
}

How to display the values of a class?

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();

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

User defined type conversions in C++

I'm new to C++
below is the code for converting object of english distance(feet' inches") to meters and vice versa
#include <iostream>
using namespace std;
class Distance
{
private:
const float MTF;
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0), MTF(3.280833F) //no argument constructor
{ }
Distance(float meters) : MTF(3.28033F)//(1-arg constructor)
{//coverting metres to distance object
float fltfeet = MTF * meters;
feet = int(fltfeet);
inches = 12*(fltfeet-feet);
}
Distance(int ft, float in) : feet(ft), inches(in), MTF(3.280833F)
{ }
void getdist()//get distance from user
{
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() const // o/p the distance
{ cout << feet << "\'-" << inches << '\"'; }
operator float() const //conversion operator
{ // converts distance to meters
float fracfeet = inches/12;
fracfeet += static_cast<float>(feet);
return fracfeet/MTF;
}
};
int main()
{
float mtrs;
Distance dist1 = 2.35F; //meters to distance
cout << "\ndist1 = "; dist1.showdist();
mtrs = static_cast<float>(dist1); //casting distance to meters
cout << "\ndist1 = " << mtrs << " meters\n";
Distance dist2(5, 10.25);
mtrs = dist2; //casting dist2 to meters
cout << "\ndist2 = " << mtrs << " meters\n";
Distance dist3; //new object dist3
dist3 = mtrs; //here is the error
//not converting meters to distance object
cout<<"\ndist3 = ";dist3.showdist();
return 0;
}
but the code shows the error :
In member function 'Distance& Distance::operator=(const Distance&)':
error: non-static const member 'const float Distance::MTF', can't use default assignment operator
should'nt it be converting mtrs to object dist3 ?
why error occurs?
You error is actually with the line
dist3 = mtrs;
not
Distance dist3;
The reason for this is Distance has a const member variable. Since it is const it cannot be assigned to which cause the default copy assignment and move assignment operators to be deleted.
You are going to have to rethink your design if you want to allow assignment of your objects or write your own custom assignment functions.
You have to override assignment operator. And the code should be as shown below
#include <iostream>
using namespace std;
class Distance
{
private:
const float MTF;
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0), MTF(3.280833F)
{ }
Distance(float meters) : MTF(3.28033F)
{
float fltfeet = MTF * meters;
feet = int(fltfeet);
inches = 12*(fltfeet-feet);
}
Distance(int ft, float in) : feet(ft), inches(in), MTF(3.280833F)
{ }
void getdist()
{
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() const
{ cout << feet << "\'-" << inches << '\"'; }
operator float() const
{
float fracfeet = inches/12;
fracfeet += static_cast<float>(feet);
return fracfeet/MTF;
}
Distance& operator=(const Distance & otherD)
{
feet = otherD.feet;
inches = otherD.inches;
return *this;
}
};
int main()
{
float mtrs;
Distance dist1 = 2.35F;
cout << "\ndist1 = "; dist1.showdist();
mtrs = static_cast<float>(dist1);
cout << "\ndist1 = " << mtrs << " meters\n";
Distance dist2(5, 10.25);
mtrs = dist2;
cout << "\ndist2 = " << mtrs << " meters\n";
Distance dist3; //here is the error
dist3 = (Distance)mtrs ;
//cout<<"\ndist3 = ";dist3.showdist();
return 0;
}
Like another user said, you have a "const" variable, so you have to override assigment operator to address your requirements.
If you want to have class scope constant, you better change your class definition to:
class Distance
{
private:
static constexpr float MTF = 3.280833F;
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0)
...
This will eliminate error you get and will work as you intended. Plus you do not have to define that constant value multiple times as you have in your code.
Note: if you cannot use C++11 you can make MTF global constant (better in unnamed namespace inside cpp file) or just static member. Either way it will eliminate the error and you will need to define it only once, which is less error prone.
I gather that the error comes at the line
dist3 = mtrs;
The problem here is that Distance does not have an assignment operator that takes an argument of type float, so the compiler tries to create a temporary object of type Distance and construct it with the argument mtrs; that's okay, but the next step is to assign that temporary value to dist3, and the compiler is complaining that it can't assign the value of MTF in the temporary object to the value of MTF in dist3 because MTF is const.
Because of that const, objects of type Distance cannot be assigned. So, for example, dist3 = dist2 would also fail. That's probably not what you intended, and you can fix this by adding an assignment operator that simply ignores the value of MTF.
The error occurs, because you could not declare const inside a class. You should define the const variable outside the class. You should replace const float MTF with float MTF here.
As stated in other answers, the issue is that you have declared the MTF variable as const. There are ways around this though. You've set the variable to be const because it's a constant and shouldnt change. Instead, add a dedicated Distance& operator=(float feet) Method in which you actually set the feet and inches variable when passed in a float value:
class Distance
{
private:
/* ... */
public:
/* ... */
Distance& operator=(float feet)
{
// Set the feet and inches here from
// the passed feet variable
return *this;
}
};
That should solve the problem of assigning the variable from a float.

Fahrenheit to Celsius converter won't output the correct values? [C++]

Im new to C++ so I am trying to do small projects to help me learn. When I try to run my program, the fahrenheit values print properly, but the celsius value prints as a series of numbers and letters.
Here is my code
#include <iostream>
using namespace std;
double conversion( double& fahrenheit, double celsius)
{
celsius = (fahrenheit - 32.0) * (5.0/9.0);
return celsius;
}
int main()
{
double fahrenheit;
for ( fahrenheit = -40.0; fahrenheit <= 220.0;)
{
cout << fahrenheit << "F = " << conversion << "C" << endl;
fahrenheit = fahrenheit + 10.0;
}
system( "pause" );
return 0;
}
Since nobody else wants to explain their work, here goes...
double conversion( double& fahrenheit, double celsius)
Okay, the problem here is your code's design is unclear. With this declaration, you're telling people that:
It converts something, but who knows what? Remember that unlike other languages like Objective-C, the names fahrenheit and celsius don't appear at the point the function is called. FIX: Name it after what it does, e.g. fahrenheit_to_celsius or just degF2degC.
It returns a double, apparently a celsius temperature. This is good.
Its first parameter is a reference to a double. This means that you're probably going to change it. But why would it need to change fahrenheit, its input? FIX: It doesn't. Just pass it as a double, no reference.
Its second parameter is a double, apparently a Celsius temperature. But why, though? If the caller could provide the Celsius temperature, it wouldn't need to call your function. FIX: You could change this to a double& so the function could set the Celsius temperature. But there is no reason to do that because it's already returning that temperature as the function's return code. BETTER FIX: Get rid of the parameter.
Thus the function's API should look more like:
double degF2degC(double fahrenheit)
Much simpler.
{
celsius = (fahrenheit - 32.0) * (5.0/9.0);
return celsius;
}
This part is basically fine. But we got rid of the double celsius (which BTW was a copy of the parameter passed in, and thus changes in this function won't be seen by the caller), so we need to make sure it's declared:
{
double celsius = (fahrenheit - 32.0) * (5.0/9.0);
return celsius;
}
But honestly, since you do nothing else with it, you should just eliminate the variable:
{
return (fahrenheit - 32.0) * (5.0/9.0);
}
for ( fahrenheit = -40.0; fahrenheit <= 220.0;)
{
cout << fahrenheit << "F = " << conversion << "C" << endl;
fahrenheit = fahrenheit + 10.0;
}
The fundamental problem here is that conversion (now degF2degC) by itself is a function. It doesn't call the function; to do that you have to add (fahrenheit). Without that, if this compiles, it will be because C++ will convert conversion to a function pointer, which isn't really useful to you.
That said, there are a few things that could be done better. First, the for statement is for(initializer; condition; step-expression) so the fahrenheit = fahrenheit + 10.0; should really be the step expression. Someone who hasn't read all the code could think this was an infinite loop.
Second, since you only use fahrenheit (which, BTW, is not the same fahrenheit object as in the function) in the loop, you can declare it in the initializer and remove the separate double fahrenheit; line.
Third, you can use the += operator to avoid repeating fahrenheit.
Putting all this together, you get:
int main()
{
for (double fahrenheit = -40.0; fahrenheit <= 220.0; fahrenheit += 10.0)
{
cout << fahrenheit << "F = " << degF2degC(fahrenheit) << "C" << endl;
}
system( "pause" );
return 0;
Unless you're running this in a window that closes immediately on program completion, you don't need system( "pause" );.
#include <iostream>
using namespace std;
double conversion( double fahrenheit) //needs only one argument
{
double celsius = (fahrenheit - 32.0) * (5.0/9.0);
return celsius;
}
int main()
{
double fahrenheit;
for ( fahrenheit = -40.0; fahrenheit <= 220.0;fahrenheit = fahrenheit + 10.0;)
{
cout << fahrenheit << "F = " << conversion(fahrenheit) << "C" << endl;
}
system( "pause" );
return 0;
}
double F2C(double fair){
double celc = (fair - 32.0) / 1.8;
return celc;
}
double C2F(double celc){
double fair = 1.8 * celc + 32
return fair;
}
there you are
also, here is a function mock up
<type of value that is returned> <function name> (<parameters>){
<function body>;
return <value that is returned>;
}
and here is a function call
<name of function>(<function's parameters>);
C2F for instance, is called like this;
double myFahrenheitValue = C2F(22.0);
printing myFahrenheitValue with std::cout will output 71.6