Help with simple output code

Hi All :)

I'm having some difficulty with a certain code i'm doing.

im trying to figure out why the code won't output the Celsius answer in a whole number rather the 4 decimals points its putting out. Here is the code

#include <iostream>
using namespace std;
class con
{
public:
float f;
float convert() {
return (((f - 32) / 9) * 5);
}
};
int main() {
float c;
con ob1;
cout << "Enter Temperature in Fahrenheit : ";
cin >> ob1.f;
c = ob1.convert();
cout << "Temperature in Celsius : " << c;
system("pause");

The code builds good just that one issue. it outputs the answer in decimals.

Any help would be appreciated :)
Last edited on
closed account (2LzbRXSz)
Because you are using float instead of int

I just changed it to int, and it now outputs a whole number:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
class con
{
public:
    int f;
    int convert() {
        return (((f - 32) / 9) * 5);
    }
};
int main() {
    int c;
    con ob1;
    cout << "Enter Temperature in Fahrenheit : ";
    cin >> ob1.f;
    c = ob1.convert();
    cout << "Temperature in Celsius : " << c;
    // system("pause");
}


By the way, it's really recommended that you don't use system functions. When I need to pause, I like to use sleep_for which you can read about here. http://www.cplusplus.com/reference/thread/this_thread/sleep_for/ There really isn't any reason for you to pause there though? I actually recommend erasing that line, or replacing it with return 0; so that your program ends.

Your main function was also missing it's closing curly bracket, so I fixed that :)

If you don't mind me asking, why are you using a class in place of a function? Any reason in particular?
Last edited on
@cactus
Thank You very much. i really appreciate it.
And the reasoning for the class rather than a function is because i'm trying out different approaches to building the code. More of like exploring different approaches. Using class for a code like this isn't all that popular but i'm just trying something new. anyways Thank you :)
i still have lots to learn but thank you for your help int rather than float thank you:) and the system pause i use that cause on visual studio when i debug the program the box just closes when i input the Fahrenheit number. but ill look into the sleep_for :) Thanks :)
closed account (2LzbRXSz)
No problem, anytime:)

That's really great, always new to expand your coding horizons! I was just wondering, because as you said, it's not really popular. It still works all the same.

Oh, that makes sense then. sleep_for is just a better alternative, since it's cross platform and isn't a system function.
Topic archived. No new replies allowed.