Question regarding using only setters and variables correctly

前端 未结 2 1242
梦毁少年i
梦毁少年i 2021-01-25 09:26

I am having an issue with my current programming assignment. I feel as though I am very close to having it correct, but something is off. I know that I have to do something diff

相关标签:
2条回答
  • 2021-01-25 09:46

    Just use one specific unit to store the temperature internally, best would be Kelvin1 IMO (as it's the standard SI physical unit).

    Do the necessary calculations when setting or getting the temperature as Fahrenheit or degrees Celsius.

    Also don't use integer division to represent fractions:
    (5/9) will result as 0 integer division, it should be (5.0/9.0) to get a valid double value.
    Same with 9/5 as integer division will result as 1.


    Further issues with your code:

    1. In your function double converter(double temperature) you try to use f, which isn't in scope there
    2. In that same function you have a parameter named temperature, which shadows your member variable with the same name

    1)0K = -459,67F / 0K = -273.15°C

    0 讨论(0)
  • 2021-01-25 10:03

    Your issue is because you are trying to compare the temperature value to the initial variable name in order to determine if it is Fahrenheit or Celsius.

    if (temperature = f)
    ...
    else if (temperature = c))
    

    You should choose one temperature type over the other to always store the value as and convert for the other when needed. In this example Celsius is used.

    void set_celsius(double c)
    {
        temperature = c;
    }
    void set_fahrenheit(double f)
    {
        temperature = (5.0/9.0)(f - 32);
    }
    

    The same can be done with your getter for Fahrenheit. Your converter method really isn't needed (and not being called atm).

    EDIT

    You should also be using floating point math as integer math will be truncated to 0 since the value you are after is a decimal, 0.5555...

    Storing the value as one of the desired temperatures will save on calculations when that temperature type is needed. In this code, it wouldn't make a difference but when scaling software up it's important to eliminate excessive processing.

    0 讨论(0)
提交回复
热议问题