Reputation: 191
I'm trying to write a function that can, given one, convert between to all four of Kilometers, Miles, Nautical Miles, and Furlongs given one of the four. My Main function looks like:
int main() {
Scale scale; // declared in the header file "length.h"
double value, kilometers, miles, nautical_miles, furlongs;
// prompt user for unit to convert from
printf("\nPlease select which unit you want to convert from:\n");
printf("1. Kilometers\n2. Miles\n3. Nautical Miles\n4. Furlongs\n");
scanf("%d", &scale);
// Get value user wants
printf("Enter value for unit you selected: ");
scanf("%d", &value);
int err = convertLength(&kilometers, &miles, &nautical_miles, &furlongs, scale);
printf("value given was %d\n", value);
kilometers *= value;
//kilometers *= 2;
//kilometers = kilometers * value;
printf("%g Kilos\n%g miles\n%g naut mi\n%g fur", kilometers, miles, nautical_miles, furlongs);
return 0;
}
The conversion is taking place in the file "length.c" and I have only been debugging the kilometers case so far. The Enum declaration for scale is in a header file "length.h".
The issue is that when I multiply kilometers in main() by value, I get an incorrect result (such as 4.940e-324). However, when I only multiply by a constant, like the commented out line //kilometers *= 2; I will get the correct answer (2 in that case). What's going wrong with the variable value that's making it behave in this way?
int convertLength(double *kilometers, double *miles, double *nautical_miles, double *furlongs, Scale scale) {
switch(scale) {
case KILOMETERS:
printf("Kilometers was chosen\n");
*kilometers = 1;
*miles = 1/1.609347219;
*nautical_miles = *miles * 1.15078;
*furlongs = *miles / 8;
break;
Upvotes: 0
Views: 61
Reputation: 53006
Change scanf()
's specifier, for double
it is "%lf"
, not "%d"
, also
Turn on compiler warnings to avoid this kind of mistake, it should warn you about the incompatibility between the passed pointer and the expected pointer.
Check scanf()
's return value to ensure that your data is find instead of just assuming that it is.
Upvotes: 4