Informatics - Length Converter Version 2 (Week 15)
Hmm last week we made a length converter from feet to meters and otherwise. Now, I'll show you how to convert centimeters to inch. But here, there will be some addition rather just to change the code. The addition is we will make a do-while loop. In this program, the do-while loop is used to keep asking for input and performing the conversion. If the user enters a negative number, it prints "error" and stops with a break.
Here's the code of the centimeters to inch length converter:
//program ConverCm2Inch.cpp
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
double cm, inch;
void cm2inch(){
do{
cout << "Enter value in cm: ";
cin >> cm;
if (cm < 0){
cout << "ERROR";
break;
}
inch = cm * 2.5;
cout << cm << "is equal to: " << inch << "inch";
}while (cm < 0);
}
void inch2cm (){
do {
cout << "Enter value in inch: ";
cin >> inch;
if (inch < 0){
cout << "ERROR";
break;
}
cm = inch/2.5;
cout << inch << "is equal to: " << cm << "cm";
}while (inch < 0);
}
int main(){
int choice;
cout << "Choose the program! \n";
cout << "1. cm to inch \n";
cout << "2. inch to cm \n";
cout << "My choice is: \n";
cin >> choice;
switch (choice){
case 1:
cm2inch();
break;
case 2:
inch2cm();
break;
default:
cout << "ERROR ERROR ERROR";
}
}
The do-while loop in this code is used to get user input, check if it's valid, and perform the conversion.
How it works:
- The loop asks the user to enter a value (either in cm or inches).
- If the value is negative, it prints "ERROR" and stops (break;).
- If the value is valid (not negative), it performs the conversion.
- The while (cm < 0); or while (inch < 0); condition is meant to repeat if the value is negative, but since the loop contains break;, it actually stops immediately when a negative number is entered.
Besides of the do-while loop the structure of the rest of the code is just the same. You only need to change the unit length then adjust the suitable conversion from centimeters to inch and so on.
It's easy isn't it? So from now on you can make your own length converter. I'm sure it's really helpful for everyone who needs this. Enjoy!
Komentar
Posting Komentar