指针传输错误
程序代码:
int set_mode(int mode) { if(mode != 0 && mode != 1) { printf("Invalid mode specified.mode \"1\" (us) used.\n"); mode = 1; } return mode; } // 按照模式获取相应的距离和油耗 double * get_info(int mode) { double distance; double oil; double ch[3]; double * ptr; if(mode != 1) { printf("Enter distance traveled in kilometers: "); while(1 != scanf("%lf",&distance)) if('\n' != getchar()) continue; printf("Enter fuel consumed in liters: "); while(1 != scanf("%lf",&oil)) if('\n' != getchar()) continue; } else { printf("Enter distance traveled in miles: "); while(1 != scanf("%lf",&distance)) if('\n' != getchar()) continue; printf("Enter fuel consumed in gallons: "); while(1 != scanf("%lf",&oil)) if('\n' != getchar()) continue; } ch[0] = distance; ch[1] = oil; ch[2] = mode; return ch; // 此时ch[0] ch[1] ch[2] 还是输入的正确值 } // 计算并显示燃料消耗值 void show_info(double ptr[]) { double mode; mode = ptr[2]; if(mode != 1) { printf("Fuel consumption is %.2f liters per 100 km\n",(ptr[1] / ptr[0]) * 100); // 这边ptr[0]ptr[1]ptr[2] 三个值错误了 这是为什么? } else printf("Fuel consumption is %.2f liters per gallon\n",ptr[0] / ptr[1]); } //============================================= #include<stdio.h> int main(void) { int mode; printf("Enter 0 for metric mode, 1 for US mode: "); while(scanf("%d",&mode) && mode >= 0) { show_info(get_info(set_mode(mode))); printf("enter 0 for metric mode, 1 for US mode"); printf("(-1 to quit): "); } printf("Done.\n"); return 0; }
问题在注释中提了
[ 本帖最后由 SaberLion 于 2014-2-10 14:04 编辑 ]