converting 5 temperatures from fahrenheit to celsi

2019-09-26 02:23发布

问题:

This question already has an answer here:

  • C program to convert Fahrenheit to Celsius always prints zero 8 answers

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.