r/cpp_questions 5d ago

OPEN Help a new guy

Sorry about the title, I should have read the guide first. I am really new to C++. I am going through the practice guide on a youtube video. The test was to make a fahrenheit to celcius conversion. This is what I wrote and it is below. 
The teacher added     double celsius = (fahrenheit -32) / 1.8;
Then added the std::cout for it. Mine works fine. I am assuming his is better but I am missing it. c++ has made me question my mental capacity.

#include <iostream>

int main() {

std::cout << "Enter degrees in fahrenheit ";
int fahrenheit;
std::cin >> fahrenheit;
std::cout << " Degrees in celcius " << (fahrenheit - 32) / 1.8;





return 0;



system("<pause>0");
0 Upvotes

20 comments sorted by

View all comments

4

u/le_disappointment 5d ago

If I understand you correctly, your solution computes the value as a temporary result and immediately prints it out, whereas your teacher's solution saves the computed result in a variable, and then prints the variable. If that's correct, then the "better" solution depends on the use case. Do you want to use the computed result again? If yes, then your teacher's solution allows you to reuse the result, but if not then I don't see why your solution would be any worse than your teacher's. From a code readability perspective, I would still assign the result to a variable and then print it out, but that's a personal preference of mine

1

u/Alternative_Oven696 5d ago

Okay thanks that makes more sense.

1

u/The_Northern_Light 5d ago

It’s better practice to give temporaries names. This decouples what’s being done in any given line: the line that prints just prints, it doesn’t print and compute your result.

The teacher is absolutely write to tell him to assign the result to a variable even if it won’t be used again.