ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
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;
}
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.
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.
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$
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.
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).
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?
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.
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
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.