#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int KUnit;
float K;
cout << "Enter 0 for SI Units and Press 1 for US customary units: ";
cin >> KUnit;
if (KUnit == 0)
{
cout << "k = " << K << " watts/mK" << endl;
}
else if (KUnit == 1)
{
cout << "k = " << K << " BTU/hr-ft F deg" << endl;
K = K * 0.5779;
}
else
{
cout << "Invalid unit, please try again";
return 1;
}
// output
cout << "Thermal Conductivity " << K << KUnit << endl;
return 0;
}
The output becomes Thermal Conductivity 0.290
or Thermal Conductivity 0.291
The output adds a 0 or 1 coming from the initial prompt. I'm not sure if there's a way for me to change it. Is there a way for KUnit
to output "watts/mK"
or "BTU/hr-ft F deg"
as the user inputs 0 or 1? Using an if-else
structure.
CodePudding user response:
you could store the text "watts/mK"/"BTU/hr-ft F deg" on a string and then, print it:
int main() {
int KUnit;
float K;
cout << "Enter 0 for SI Units and Press 1 for US customary units: ";
cin >> KUnit;
std::string KUnitStr;
if (KUnit == 0) {
KUnitStr = " watts/mK";
} else if (KUnit == 1) {
KUnitStr = " BTU/hr-ft F deg";
K = K * 0.5779;
} else {
cout << "Invalid unit, please try again";
return 1;
}
// output
cout << "k = " << K << KUnitStr << endl;
cout << "Thermal Conductivity " << K << KUnitStr << endl;
return 0;
}
CodePudding user response:
Cache the units in a variable on your way through the existing if
statement ladder and print it out in the output line.
Eg:
#include <iostream>
#include <iomanip>
int main()
{
int KUnit;
float K;
// Added: get value from user
std::cout << "Enter value to convert: ";
std::cin >> K;
std::string units; // Added: holds user-provided units
std::cout << "Enter 0 for SI Units and Press 1 for US customary units: ";
std::cin >> KUnit;
if (KUnit == 0)
{
std::cout << "k = " << K << " watts/mK" << std::endl;
units = "watts/mK"; // added: store metric units
}
else if (KUnit == 1)
{
std::cout << "k = " << K << " BTU/hr-ft F deg" << std::endl;
K = K * 0.5779;
units = "BTU/hr-ft F deg"; // added: store imperial units
}
else
{
std::cout << "Invalid unit, please try again";
// added: nothing to store
return 1;
}
// output. changed: displays units.
std::cout << "Thermal Conductivity " << K << units << std::endl;
return 0;
}