LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-24-2010, 08:01 AM   #1
portia
Member
 
Registered: Oct 2009
Distribution: Slackware
Posts: 112

Rep: Reputation: 20
temperature converter in C - feedback


I'm a C newbie. Just wrote this temperature converter. I know it's very basic but, as it is, is there anything wrong with it? any things that are done incorrectly? It seems to work fine.

Code:
#include <stdio.h>

int main(void)
{
  float fahr, celc, result;
  int choice;

  printf("\nThis is a temperature converter!!!");
  printf("\nWhat would you like to convert?");
  printf("\n1. C to F.");
  printf("\n2. F to C.\n");

  scanf("%d", &choice);
  switch(choice)
    {
    case 1:
      printf("\nConverting from C to F\n");
      printf("\nType the temperature in C: ");
      scanf("%f", &celc);
      result=celc*1.8+32;
      printf("\n%.2fC is equal to %.2fF\n", celc, result);
      break;
    case 2:
      printf("\nConverting from F to C\n");
      printf("\nType the temperature in F: ");
      scanf("%f", &fahr);
      result=(fahr-32)*5/9;
      printf("\n%.2fF is equal to %.2fC\n", fahr, result);
      break;
    default:
      printf("\nError!!! You have not provided a valid choice!!!\n");
      break;
   }
  return 0;
}

gracias

Last edited by portia; 09-24-2010 at 08:03 AM.
 
Old 09-24-2010, 09:25 AM   #2
H_TeXMeX_H
LQ Guru
 
Registered: Oct 2005
Location: $RANDOM
Distribution: slackware64
Posts: 12,928
Blog Entries: 2

Rep: Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301
Well one thing for sure, do NOT use float, use double.

Also, why did you use 1.8 instead of 9/5 ? and yet in the other calculation you used 5/9 ? Using the fraction is more accurate.
 
Old 09-24-2010, 09:26 AM   #3
theNbomr
LQ 5k Club
 
Registered: Aug 2005
Distribution: OpenSuse, Fedora, Redhat, Debian
Posts: 5,399
Blog Entries: 2

Rep: Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908
Looks good to me. The only thing I could add would be to call exit() with a non-zero value for erroneous menu selection. This would be consistent with normal Unix practice. You could add some validation for bogus user entry, but I cannot see a single point to take issue with in the existing code.

--- rod.
 
Old 09-24-2010, 11:21 AM   #4
GazL
LQ Veteran
 
Registered: May 2008
Posts: 6,899

Rep: Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020
Initialise choice = 0 before you call scanf() just in case the call fails. You don't want to inherit a bogus value that may have been occupying that memory location previously. It's always a good idea to set variables to a known state before you use them.


You might also want to think about what would happen if someone answers 'C' or 'F' instead of 1 or 2.

At the simplest level you could just do something like
Code:
if ( scanf("%d", &choice)  !=  1 ) {
   fprintf(stderr, "What the hell was that supposed to be?\n");
   return 1;
}
but, you could enhance it by checking for other errors and perhaps even offering the user another chance to enter a sensible value by putting it in a loop.

If you don't feel ready for that yet, then you could always revisit the code and make it a little more robust as a exercise for later.

Best of luck with your learning. I'm currently doing the same. Most important thing is to have fun with it.
 
1 members found this post helpful.
Old 09-24-2010, 11:39 AM   #5
GazL
LQ Veteran
 
Registered: May 2008
Posts: 6,899

Rep: Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020Reputation: 5020
Quote:
Originally Posted by H_TeXMeX_H View Post
Well one thing for sure, do NOT use float, use double.

Also, why did you use 1.8 instead of 9/5 ? and yet in the other calculation you used 5/9 ? Using the fraction is more accurate.
Doesn't C do integer math if you use constants without a decimal point?
I can vaguely remember something about that in the book I'm reading.
so you'd have to write it as 5.0/9 ?

Code:
gazl@nix:~/projects/C$ cat math.c
#include <stdio.h>
#include <errno.h>

int main()
{

    double result;
    
    result = 5/9;
    printf("%f\n", result);
    result = 5.0/9;
    printf("%f\n", result);
    return 0;
}
gazl@nix:~/projects/C$ cc math.c && ./a.out
0.000000
0.555556
gazl@nix:~/projects/C$
 
1 members found this post helpful.
Old 09-24-2010, 12:29 PM   #6
portia
Member
 
Registered: Oct 2009
Distribution: Slackware
Posts: 112

Original Poster
Rep: Reputation: 20
I'd like to thank you people for your feedback. It's really helpful.

Quote:
Well one thing for sure, do NOT use float, use double.
Why is that? As far as I know (which is not very far, the only difference between float and double is the precision (float- 6 digit precision, double: 15 digit precision). Isn't float enough to do temperature conversions like that? Does the problem lie somewhere else?
Quote:
Also, why did you use 1.8 instead of 9/5 ? and yet in the other calculation you used 5/9 ? Using the fraction is more accurate.
I didn't think much about the maths aspect of it.

Quote:
Looks good to me. The only thing I could add would be to call exit() with a non-zero value for erroneous menu selection. This would be consistent with normal Unix practice. You could add some validation for bogus user entry, but I cannot see a single point to take issue with in the existing code.
acknowledged

Quote:
Initialise choice = 0 before you call scanf() just in case the call fails.
I'll remember about it in the future.

Code:
if ( scanf("%d", &choice)  !=  1 ) {
   fprintf(stderr, "What the hell was that supposed to be?\n");
   return 1;
}

Thanks. I'll need to read on 'fprintf' (never seen it before) otherwise it makes sense. It'd probably be even better to combine checking for 1 AND 2 at the same time. Otherwise, I could use 'else if'.
Quote:
Doesn't C do integer math if you use constants without a decimal point?
I can vaguely remember something about that in the book I'm reading.
so you'd have to write it as 5.0/9 ?
You come back to what TexMex pointed out. That's still slightly confusing me. Sometimes you need to do what I read is called 'casting'. I don't know which types to use/ or when to write 5.0 as opposed to 5.
I'm sure it's not rocket science but it was only 2 days ago that I first read about floats, doubles, floating-point operations,etc.
 
Old 09-24-2010, 01:49 PM   #7
H_TeXMeX_H
LQ Guru
 
Registered: Oct 2005
Location: $RANDOM
Distribution: slackware64
Posts: 12,928
Blog Entries: 2

Rep: Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301
Quote:
Originally Posted by GazL View Post
Doesn't C do integer math if you use constants without a decimal point?
I can vaguely remember something about that in the book I'm reading.
so you'd have to write it as 5.0/9 ?

Code:
gazl@nix:~/projects/C$ cat math.c
#include <stdio.h>
#include <errno.h>

int main()
{

    double result;
    
    result = 5/9;
    printf("%f\n", result);
    result = 5.0/9;
    printf("%f\n", result);
    return 0;
}
gazl@nix:~/projects/C$ cc math.c && ./a.out
0.000000
0.555556
gazl@nix:~/projects/C$
Yes, you are obviously right, I forgot about that. If you wanted it to make it more clear you can do:

Code:
result = (double)5/9;
As for the rest, it is to your advantage to use double, in most cases it is both faster and more accurate.

I don't know about the quality and accuracy that you require from this program, but my C teacher would have surely taken off points for all of the above (mostly because she was impossible, yet correct).
 
Old 09-27-2010, 02:53 AM   #8
portia
Member
 
Registered: Oct 2009
Distribution: Slackware
Posts: 112

Original Poster
Rep: Reputation: 20
Quote:
As for the rest, it is to your advantage to use double, in most cases it is both faster and more accurate.
Sorry, It doesn't make sense to me How can something that takes more memory be quicker to process?

I've also got some related questions. Consider the following program:

Code:
int main(void)
{
  int number = 0;                      /* Stores a number             */
  int count = 10;                      /* Number of values to be read */
  long sum = 0L;                       /* Sum of the numbers          */
  float average = 0.0f;                /* Average of the numbers      */

  /* Read the ten numbers to be averaged */
  for(int i = 0; i < count; i++)
  {
    printf("Enter grade: ");
    scanf("%d", &number);              /* Read a number */
    sum += number;                     /* Add it to sum */
  }

  average = (float)sum/count;          /* Calculate the average */

  printf("\nAverage of the ten numbers entered is: %f\n", average);
  return 0;
}

Do we have to append the L and f letters as in "long sum = 0L;". If not, what's the benefit?

If the variable "sum" has to be cast for a floating-point operation
why not create it as a float in the first place?
 
Old 09-27-2010, 04:52 AM   #9
H_TeXMeX_H
LQ Guru
 
Registered: Oct 2005
Location: $RANDOM
Distribution: slackware64
Posts: 12,928
Blog Entries: 2

Rep: Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301
Here's why, from my C book it says (actually from my notes on my C book):

Floating point constants (not const, but non-variables), are assumed to be doubles. During calculations, other types (float) are promoted (to double), and after the calculation, if the answer is stored as float, it is demoted, which reduces speed and accuracy. To override this, add 'f' or 'F' suffix, ex. 2.3F, or for long double, ex. 54.3L, use 'L'. Otherwise it is assumed to be double.

Hope that answers some questions.

Again, NEVER use float, use double. That's why my C teacher told me, and I think it's true. She took points off for this.
 
Old 09-27-2010, 05:20 AM   #10
grail
LQ Guru
 
Registered: Sep 2009
Location: Perth
Distribution: Manjaro
Posts: 10,007

Rep: Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192Reputation: 3192
I have no particular technical advice as that seems to have been covered, but thought I would add to GazL's input on checking the input from the user for entering 1 or 2 at the start.
As we are aware, humans are particularly visual but reading is left to the user's imagination (ie tihs is siltl raedlbae) so help the user by advising what you would like to be entered
prior to the choices, lie:
Code:
printf("\nThis is a temperature converter!!!");
printf("\nWhat would you like to convert?");
printf("\n(Please enter a 1 or 2 to select from below)");
printf("\n1. C to F.");
printf("\n2. F to C.\n");
Otherwise I thought it looked very good for a first try
 
Old 09-27-2010, 06:41 AM   #11
graemef
Senior Member
 
Registered: Nov 2005
Location: Hanoi
Distribution: Fedora 13, Ubuntu 10.04
Posts: 2,379

Rep: Reputation: 148Reputation: 148
First a point on the first problem that I don't think anyone else has pointed out. You don't need the result variable.

On your second problem post #8. Integer calculations are quicker than floating point so in the loop it makes sense to keep sum as an integer.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
temperature and volume MightyKC Linux - Hardware 7 06-09-2007 05:13 PM
Laptop Temperature boxxa Linux - Laptop and Netbook 6 08-19-2005 10:01 AM
temperature monitor Sinatra Linux - Software 5 07-20-2004 01:53 PM
temperature monitor Pinkdog Linux - Software 3 11-17-2003 09:38 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 03:52 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration