I’m working on an application for converting Celsius to Fahrenheit and vice versa.
The application contains of fields and radiobuttons. The user fills in “start temperature”, “end temperate” and “iterator” and chooses to convert from C to F or F to C.
After clicking a button a table is rendered showing the temperature in C and the converted temperature in F (or vice versa). I’ve tried to do it with a while-loop as well as a for loop, but it doesn’t work as it shall.
I know that it is an unnecessary complex solution, and I really should appreciate help with creating a more elegant solution, that works.
var i = 0;
while (startTemp < endTemp) {
i += 1;
TableRow tRow = new TableRow();
tRow.CssClass = (i % 2 == 0 ? "white" : "grey");
tempTable.Rows.Add(tRow);
startTemp = startTemp + iterator;
if (startTemp < endTemp) {
for (int j = 0; j <= 1; j++) {
TableCell tCell = new TableCell();
if ((j % 2) == 0) {
tCell.Text = startTemp.ToString();
}
else {
if (tempType1 == "°C") {
convertedTemp = TemperatureConverter.CelsiusToFahrenheit(startTemp);
}
else {
convertedTemp = TemperatureConverter.FahrenheitToCelsius(startTemp);
}
tCell.Text = convertedTemp.ToString();
}
tRow.Cells.Add(tCell);
}
}
Wanted output (iterator = 2):
C——————–F
39 102
41 105
43 109
45 113
47 116
49 120
EDIT: The solution works fine, except for one thing. If I use 1 as start temp, 10 as end temp and 1 as iterator, it stops at 9 (not at 10 as it should), and I just can’t figure out why.
Your solution is good but I would do only 1 loop
yours stop at 9 because
at the begining of your while loop you do 9+=1
so i = 10 then if(10 < 10)
so it stops there
So you could do if(startTemp <= endTemp)