Problems with accessor and mutator functions of class - c++

I'm trying to write a simple program that takes in a Kelvin temperature input from the user, and output the Farneheit and Celsius conversions of it. However, for a Kelvin input of 273.15, my program keeps outputting strange numbers like "6.95274e-310" for Farenheit and "4.6519e-310" for Celsius. I believe there is a problem with the accessor and mutator functions within the class, but I'm not quite sure what the issue is.
#include <iostream>
using namespace std;
class Temperature{
private:
double Kelvin;
double Celsius;
double Farenheit;
public:
void setKelvin(double);
void setCelsius();
void setFarenheit();
double getKelvin();
double getCelsius();
double getFarenheit();
};
void Temperature::setKelvin(double x){
Kelvin = x;
}
void Temperature::setCelsius(){
Celsius = Kelvin-273.15;
}
void Temperature::setFarenheit(){
Farenheit = (Celsius/(5.0/9))+32;
}
double Temperature::getKelvin(){
return Kelvin;
}
double Temperature::getCelsius(){
return Celsius;
}
double Temperature::getFarenheit(){
return Farenheit;
}
int main(){
cout<<"Enter a temperature in degrees Kelvin: ";
double y;
cin>>y;
Temperature K;
K.setKelvin(y);
cout<<"Temperature after converting to Celsius: ";
cout<<K.getCelsius();
cout<<"Temperature after converting to Farenehti: ";
cout<<K.getFarenheit();
}

Whenever you see weird values like this, it's very likely that these are uninitialized memory (aka garbage). It is data that was written by another application before and not been changed (initialized) by yours. That is why it's very important to always initialize variables.
Built-in types (int, char, double, etc) aren't initialized automatically: that is why you often see statements like int x(0);. Other objects, on the other hand, are initialized via the default constructor. This is why std::string str; doesn't create garbage: an empty std::string is created by std::string::string().
This behavior is clearly demonstrated in your program: Temperature::Celsius and Temperature::Farenheit are never initialized. An easy fix is to add the following lines after K.setKelvin(y):
K.setCelsius();
K.setFarenheit();
Alternative solutions may involve recalculating the Celsius and Farenheit values in their respective getters or systematically "synchronizing" them in the setKelvin method.

Related

Unsure of why I do not call the return type here in my void function definition

I am learning C++. I am following along with a learning tutorial. After creating (forgive me if I am not labeling this correctly) a function that calculates exponentials with the for() loop. We are learning how to use a void function to call it. In all of the code there are few times the parameters (hopefully labeling correctly) do not include the return type.
It is creating an itch for me as I really am taking things slow trying to understand everything so far.
#include <iostream>
double power_function(double base, double exponent)
{double solution = 1;
for(double i = 0; i < exponent; i++)
{solution = solution * base;
}
return solution;
}
void print_power(double base, double exponent)
{ double void_operation = power_function(base,exponent);
/* Why do we call without the return type? Cause it is already defined? */
std::cout << "The base of " << base << " with an exponent \n.";
std::cout << " of " << exponent << " is equal to " << void_operation;
}
int main ()
{int base test, exponent test;
std::cout << "What is the base,\n.";
std::cin >> base_test;
std::cout << "What is the exponent?\n.";
std::cin >> exponent_test;
printpower(base_test, exponent_test);
}
When you call functions in C++ you don't need to specify the return type because it's already specified in the function definition above.
Here's a really simple example of this from cplusplus.com
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
}
addition() has return type int but when its called
z = addition (5,3); the return type is not specified.
First, a function should be declared:
double power_function(double base, double exponent)
This tells the compiler that a function exists named power_function, which takes two double parameters, and returns a double. (The definition might immediately follow, or the definition might be elsewhere, but that's not relevant int his case) From then, on, the compiler knows the parameter types, and the return type.
So when the compiler sees:
double void_operation = power_function(base,exponent);
The compiler will generate code to copy both those parameters as doubles to the stack (converting them to double if needed), and then call the function. When the function returns, the compiler already knows the return type is a double, so it will take the top item on the stack as a double and will assign it to void_operation (again, converting from double if needed).

Compile Error: Function does not take 1 arguments

void displayCost();
double computeArea();
double roundCost();
int main()
{
return 0;
}
void displayCost(string name, int size)
{
double area = computeArea(size);
cout << "Since a " << size << "-inch pizza covers" << area << "square inches, "
<< name << ", then a 12 cents per square inch, the cost will be" << 12*area
<< " - which rounds to" << roundCost();
}
double computeArea(int size)
{
double radius = size/2;
double area = pi*radius*radius;
return area;
}
double roundCost(double price)
{
double roundedCost = ceil(price*100)/100;
return roundedCost;
}
It happens on the line at double area = computeArea(size);. I don't understand why it says I'm not passing an argument in when I clearly am.
double computeArea();
double area = computeArea(size);
double computeArea(int size) {
One of these things is not like the others, ...
You need to fix your prototype (the first one) to match the actual function:
double computeArea(int);
And, of course, ditto for the other prototypes as well.
You are messing up your forward declarations, they also have to reflect the type of parameters of your function.
void displayCost(string, int);
double computeArea(int);
double roundCost(double);
C++ differs from C in that a forward declaration of a function must specify the number and types of arguments. Whereas in C
double computeArea();
means that there is some function called computeArea that returns double, in C++ it is the same as
double computeArea(void);
That is, it specifies that computeArea takes no arguments.
Presumably the difference is because C++ allows functions to be overloaded, whereas C doesn't.
You've declared computeArea to take exactly zero arguments in the prototype (above main). The fact that you've then defined it to take a double down below is beside the point. Inside main, you're calling it with an argument, which, according to the prototype, is wrong.

Am getting error as "Expression must have (pointer-to-)function type" in c++

Hi i have the below code
# include <iostream>
# include <limits>
# include <cmath>
using namespace std;
class fahrenheit
{
float f,c,x;
public:
void getdata();
void display();
}
void fahrenheit::getdata()
{
cout << "Enter the value of f : ";
cin >> f;
x=f-32;
c=5/9(x); //Here i am getting error as Expression must have (pointer-to-)function type //
}
void fahrenheit::display()
{
cout << "c=" << c;
std::cin.ignore();
std::cin.get();
}
int main()
{
fahrenheit f;
f.getdata();
f.display();
}
i have given the datatype as float for the input variables , but i am not sure what should be done to rectify the error .
5/9(x) doesn't remotely look like C++. You likely meant c = 5.0 / 9.0 * x;
first of all, you forgot about a semicolon right after the class definition.
Second, I presume you wanted to multiply x by 9. Write
c=5/9*(x)
otherwise the compiler tries to find a function called 9(int x) (which is an incorrect name for a function anyway) and realizes that 9 is in no sense any function pointer but just an int.. that's what the error means.
By the way.. if you write 5/9 compiler understands it as int values being divided.
It will divide int(5) by 9 using an int / operator, which after dividing will return
floor(5/9) = 0 . If you want to have a float or double division you have to inform the compiler that your values are floats(doubles).
For doubles: 5.0/9.0*x
For floats: 5.0f/9.0f * x
You should use the multiplication operator *.
c=5/9*(x);

Calling a function in main

I'm just learning C++ and I have a little code here:
using namespace std;
int main()
{
cout<<"This program will calculate the weight of any mass on the moon\n";
double moon_g();
}
double moon_g (double a, double b)
{
cout<<"Enter the mass in kilograms. Use decimal point for any number entered";
cin>>a;
b=(17*9.8)/100;
double mg=a*b;
return mg;
}
It compiles, but when I run it it only prints out:
This program will calculate the weight of any mass on the moon
but doesn't execute the moon_g function.
This line:
double moon_g();
doesn't actually do anything, it just states that a function double moon_g() exists. What you want is something like this:
double weight = moon_g();
cout << "Weight is " << weight << endl;
This won't work yet, because you don't have a function double moon_g(), what you have is a function double moon_g(double a, double b). But those arguments aren't really used for anything (well, they are, but there's no reason to have them passed in as arguments). So eliminate them from your function like so:
double moon_g()
{
cout<<"Enter the mass in kilograms. Use decimal point for any number entered";
double a;
cin>>a;
double b=(17*9.8)/100;
double mg=a*b;
return mg;
}
(And declare the function before you call it.) More refinements are possible, but that'll be enough for now.
This is a function declaration:
double moon_g();
this won't call a function, and if you did have it correct, which means adding two parameters since that is how you define it below:
moon_g( a, b ) ;
it would not work because you either need to move the definition of moon_g before main or add a forward declaration before main like this:
double moon_g (double a, double b) ;
Although it seems like a and b are not inputs but values you want to return back to main then you would need to use references and it would need to be declared and defined like this:
double moon_g (double &a, double &b) ;
^ ^
A useful thread to read especially if you are starting out would be What is the difference between a definition and a declaration?.
Which compiler you use makes a difference here clang provides the following warning:
warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]
double moon_g();
^~
while I can not get gcc nor Visual Studio to warn me about this. It is useful in the long run to try code in different C++ compilers when you can, it can be a very educational experience and you don't have to install them either since there are plenty of online C++ compilers available online.
There is huge difference between calling a function and declaring it just as there is difference between local variables and function arguments.
I suggest reading basic tutorials first.
Anyway, thats how code should look like:
#include <iostream>
using namespace std;
double moon_g ()
{
double a,b;
cout<<"Enter the mass in kilograms. Use decimal point for any number entered\n";
cin>>a;
b=(17*9.8)/100;
double mg=a*b;
return mg;
}
int main()
{
cout<<"This program will calculate the weight of any mass on the moon\n";
cout<<"Result is: "<<moon_g();
}
There are two problems in your code.
Firstly, if you want to call your function
double moon_g (double a, double b) // this means if you want to call moon_g() you must provide arguments a and b, otherwise, the you will encounter an compile error.
{
cout<<"Enter the mass in kilograms. Use decimal point for any number entered";
cin>>a;
b=(17*9.8)/100;
double mg=a*b;
return mg;
}
you should provide the two parameters a and b.
But a and b are calculated in the body of function definition, it is unnecessary to declare the two parameters. You can write like this.
double moon_g () //this means function moon_g() does not accept any arguments
{
double a, b; // declare a and b in the definition body instead of in the arguments list
cout<<"Enter the mass in kilograms. Use decimal point for any number entered";
cin>>a;
b=(17*9.8)/100;
double mg=a*b;
return mg;
}
Then, in the main function, your calling function statement is wrong. You may want to receive the return value. So, you should write the code like this.
int main()
{
cout<<"This program will calculate the weight of any mass on the moon\n";
double ret = moon_g();
}
Finally, it is mostly recommended that the function which will be called by another function should be declared or defined previously.

Passing by value a type struct to a function, Error:two or more data types in declaration of 'average'!! -

Hello to all that read
I have a small problem(or it could be large!), just one error at compile time but as we all know one error is all it takes to hinder progress.
Basically I am fairly new to C++ and have been tasked with writing the following code and passing by value a type stuct argument to the function. But I get the following error message:
"two or more data types in declaration of average" so any solution/s to my one error would be much appreciated.
Many thanks in advance...
enter code here
#include <iostream>
#include <cstdio>
#include <math.h>
using namespace std;
struct student{
char name[40];
int student_id;
int student_grades[3];
int average;
};
int main ()
{
extern int average(student);
student programming;
int j;
cout<<"\nPlease Enter the student name for student number: ";
cin>>programming.name;
cout<<"\nPlease Enter student i.d for student number: ";
cin>>programming.student_id;
cout<<"\nPlease Enter student grades for student number: ";
for(j=0;j<3;j++){
cout<<"\nEnter student grade no: "<<j+1<<"\n";
cin>>programming.student_grades[j];
}
programming.average=average(programming);
cout<<"\nNo. Name ID Number Average\n";
cout<<programming.name;
cout<<" "<<programming.student_id <<" ";
cout<<programming.average<<" ";
system ("PAUSE");
return 0;
}
struct student;
int void average(student programming){
int sum=0;
int ave=0;
int j;
for(j=0;j<3;j++){
sum=sum+programming.student_grades [j];
}
ave=sum/3;
return ave;
}
enter code here
int void average(student programming) is not a valid syntax. There is only one return type, i.e. it should be int average(student programming).
See this?
int void average(student programming){
That's "two or more types" in a row, in the part where you say what the return type is for the function. Make up your mind.
There are several other problems with your code, mostly just stylistic. You don't want your function declaration to be extern (since it's right there in the same file); you want that declaration to be outside of main (it will work inside, but there's really no point); you don't need math.h (which is a C header anyway); you should be using a real string type to represent strings; storing the grade average back into the structure isn't especially useful (you already have it, so just use it directly); and several of your variable names don't make any sense (programming is an especially obvious example).
Your declaration of your average function should be:
int average(student programming)
You've got an extra "void" in there.