Temperature conversion issues

closed account (jwC5fSEw)
I'm trying to complete the challenge found here: http://www.cprogramming.com/challenges/celsius_converter_table.html

I have the program working as specified, but it doesn't output the right results consistently. When I put in 0 as the lower temperature, it properly gives me the temperatures (starting with 32), but when I try other numbers, the conversion is wrong. Here's the source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;

int main(){
    int step;
    float startTemp, endTemp;

    cout << "Please enter the lowest temperature in Celsius, no lower than 0: ";
    cin >> startTemp;
    cout << endl << "Please enter the highest temperature in Celsius, no lower than 10 but no higher than 1000: ";
    cin >> endTemp;
    cout << endl << "Please enter the size of the step, no higher than 10: ";
    cin >> step;

    if ((startTemp < 0) || (endTemp < 10 || endTemp > 1000) || (step > 10 || step < 0) || (step > (endTemp-startTemp)))
        cout << "You entered invalid information. Program terminating" << endl;
    else {
        int num = int((endTemp - startTemp)/step+1);
        float tempC[num], tempF[num],
        stepF = step*1.8,
        startTempF = ((9/5)*startTemp)+32;

        for (int i=0; i<num; i++){
            tempC[i] = startTemp;
            tempF[i] = startTempF;
            startTemp += step;
            startTempF += stepF;
        }

        cout << "Celsius:" << endl;
        for (int i=0; i<num; i++){
            cout << tempC[i] << endl;
        }

        cout << endl;

        cout << "Fahrenheit:" << endl;
        for (int i=0; i<num; i++){
            cout << tempF[i] << endl;
        }
    }
}


Any suggestions for why the results aren't always working?
This line here:
startTempF = ((9/5)*startTemp)+32;

(9/5) gets evaluated as integer math, which means it equals 1, not the effect you want.

Use (9.0/5.0) or just use 1.8 and you will get the results you want. When startTemp = 0, the (9/5) is also 0 so that's why it works with a value of 0.
Last edited on
closed account (jwC5fSEw)
Oh, I see. Works great now, thanks!
Topic archived. No new replies allowed.