we're supposed to write a centimeter to inch/ inch to centimeter converter
and my if statements are not working im still a newbie, can someone please tell me what i did wrong?
#include <iostream>
usingnamespace std;
void main()
{
int nb;
double value;
double result;
cout << ("1 for inch to centimeter conversion") << endl;
cout << ("2 for centimeter to inch conversion") << endl;
cout << ("please make a selection: ");
cin >> nb;
if ( nb=1 ){
cout <<("please enter the value in centimeters: ");
cin >> value;
result= value*0.39370;
cout << value << (" centimeters = ") << result << endl;
}
elseif ( nb=2 ) {
cout <<("please enter the value in inches: ");
cin >> value;
result= value/0.39370;
cout << value << (" centimeters = ") << result << endl;
}
else
cout <<(" wrong input ") << endl;
system ("pause");
}
Well, someone already explained the problem. To explain that further, from what I understand, most programming languages treat a single equals sign as if you're setting something equal to what follows the equals sign. However, a double equals sign signifies a test for that condition to be equal.
you are printing "centimeters =" in both cases.
it's best to initialise variables e.g.
1 2 3
nt nb = 0;
double value = 0.0;
double result = 0.0;
and there's duplicate code that could be refactored.
dont use usingnamespace std;
and i wouldnt use system("pause").
looks ok though :)
edit: wait a minute.. i dont think your conversion is right.
I chose 1 (inch to centimetre)
I chose 1 again (i.e. give me 1 inch in centimetres)
answer = 0.3937
Which is wrong as there's about 2 and half cm in an inch isn't there?
yea it's the other way around.
change:
1 2
cout << ("1 for inch to centimeter conversion") << endl;
cout << ("2 for centimeter to inch conversion") << endl;
to
1 2
cout << ("1 for centimeter to inch conversion") << endl;
cout << ("2 for inch to centimeter conversion") << endl;
#include <iostream>
#include <string>
int main()
{
int choice = 0;
double value = 0.0;
double result = 0.0;
constdouble conversion = 0.39370;
std::string units = " centimeters = ";
std::cout << ("1 for centimeter to inch conversion") << std::endl;
std::cout << ("2 for inch to centimeter conversion") << std::endl;
std::cout << ("please make a selection: ");
std::cin >> choice;
std::cout << ("please enter the value to convert: ");
std::cin >> value;
if (choice == 1)
{
result = value*conversion;
}
elseif (choice == 2)
{
result = value / conversion;
units = " inches = ";
}
else
{
std::cout << (" wrong input ") << std::endl;
}
std::cout << value << units << result << std::endl;
return 0;
}