converting 5 temperatures from fahrenheit to celsius [duplicate]

旧城冷巷雨未停 提交于 2019-12-25 19:32:51

问题


Every day, a weather station receives 5 temperatures expressed in degree Fahrenheit. Write a program to accept temperature in Fahrenheit, convert it to Celsius and display the converted temperature on the screen. After 5 temperatures, the message ‘All temperatures processed’ should be displayed on the screen

My answer is below

#include <stdio.h>
main()
{
  int fah, cel;
  printf("\nEnter 5 temperatures in Fahrenheit: ");
  scanf("%d %d %d %d %d", &fah);
  do
  { 
    cel=(fah-32)*(5/9);
    printf("\n These temperatures converted to Celsius are: %d \n", cel);
  }
  while(fah);
}

回答1:


scanf("%d %d %d %d %d", &fah);

You used 5 %d in the conversion specifier, but only one variable.

cel=(fah-32)*(5/9);

Here, you used integer division, change the type of the variables to double and 5/9 to 5.0/9




回答2:


Lets take this one by one -

  • scanf("%d %d %d %d %d", &fah); : You want to scan five values while you are using only one %d. What about the other four values ? You should use an array of 5 values.
  • cel=(fah-32)*(5/9); : You are dividing 5 by 9, both of which are integers. The result of dividing an integer by another, a/b, where a < b is 0. Hence cel will always be 0. You have to cast one of the integers to a float/double.
  • If you do use an array, you need to loop over all elements of the array to process them.

I am purposely not providing a direct solution to all these. I suggest you look up on these things and understand them, since they are very basic for programming in C.




回答3:


You're working in integers --> 5/9 is converted to integer 0 thus the result will also equal to 0. You need to work with float/double types or change your calculation to minimize such rounding errors, e.g. something like this: cel=(5*(fah-32))/9; - here the multiplication is done first and division after that.



来源:https://stackoverflow.com/questions/18330766/converting-5-temperatures-from-fahrenheit-to-celsius

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!