CVHansen - 1 year ago 69
C++ Question

# User input requested twice

Disclaimer: I am a 1st semester c++ student, I have no idea what I'm doing, and my textbook is beyond confusing. Also, the style of the code is mandatory for the assignment given. Please proceed with that knowledge!

OP: I have a code that converts Fahrenheit to Celsius and displays the Celsius temperature. However, it's asking for the Fahrenheit input twice. I've tried altering the code everywhere I can think (and places recommended in other threads), but it either does not fix the issue or it causes other errors and will not build properly.
Thank you in advance for your help, here's the code from my latest functional build:

``````#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

//declare function prototypes
double getFahrenheit();
double calcCelsius();

int main()
{
double fahrenheit = 0.0;
double celsius = 0.0;

//call getFahrenheit function
fahrenheit = getFahrenheit();

//call calcCelsius function
celsius = calcCelsius();

//display temperature in degrees celsius
cout << "The temperature is: " << celsius << endl;
return 0;
} //end of main function

double getFahrenheit()
{
double fahrenheitTemp = 0.0;
cout << "Enter temperature in Fahrenheit: " << endl;
cin >> fahrenheitTemp;
return fahrenheitTemp;
}

double calcCelsius()
{
double fahrenheit = getFahrenheit();
double celsiusTemp = 5.0 / 9.0 * (fahrenheit - 32.0);
return celsiusTemp;
}
``````

I believe the error is related to:

``````//call getFahrenheit function
fahrenheit = getFahrenheit();
``````

And the "double fahrenheit = getFahrenheit();" line in this function:

``````double calcCelsius()
{
double fahrenheit = getFahrenheit();
double celsiusTemp = 5.0 / 9.0 * (fahrenheit - 32.0);
return celsiusTemp;
}
``````

Again, though, I can't figure out how else to write this and still have a functional build while maintaining the structure my instructor is demanding. Really struggling with this chapter!

The problem is, as you have identified, that you call `getFahrenheit()` twice. (Actually the problem is "I have no idea what I'm doing", but let's gloss over that.) A solution is to make `fahrenheit` a parameter to `calcCelsius()`, so we get:

``````double calcCelsius(double fahrenheit);

//...

celsius = calcCelsius(fahrenheit);

//...

double calcCelsius(double fahrenheit)
{

//...
``````

That should be enough to get you close to the answer.