我试图编写一个函数,可以给出一个,在四个中的一个之间转换为全部四个公里,万里,航海里程和弗隆。我的主要功能如下:
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;
}
转换发生在文件" length.c"到目前为止我只调试了公里的情况。枚举的枚举声明位于头文件" length.h"中。
问题在于,当我将main()中的千米乘以值时,我得到的结果不正确(例如4.940e-324)。但是,当我只乘以常数时,如注释掉的行// km * = 2;我会得到正确答案(在这种情况下为2)。变量值有什么问题导致它以这种方式运行?
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;
答案 0 :(得分:4)
更改scanf()
的说明符,double
为"%lf"
,而不是"%d"
,还
启用编译器警告以避免此类错误,它应该警告您传递的指针与预期指针之间的不兼容性。
检查scanf()
的返回值,以确保找到您的数据,而不是仅仅假设它是。