【C語言】課後習題-譚浩強教授第4版
阿新 • • 發佈:2018-12-12
第8章 指標
8-1 用指標實現,輸入三個整數,按由小到大順序輸出。
自己的程式碼
#include <stdio.h> void main() { int *p1, *p2, *p3,*temp; int a, b, c; while (scanf("%D %d %d", &a, &b, &c)) { p1 = &a; p2 = &b; p3 = &c; if (a > b) { temp = p1; p1 = p2; p2 = temp; } if (a > c) { temp = p1; p1 = p3; p3 = temp; } if (b > c) { temp = p2; p2 = p3; p3 = temp; } printf("%d %d %d \n", *p1, *p2, *p3); } }
教材參考程式碼:【連結】
#include <stdio.h> void main() { void swap(int *pt1, int *pt2 ); int *p1, *p2, *p3,*temp; int a, b, c; while (scanf("%D %d %d", &a, &b, &c)) { p1 = &a; p2 = &b; p3 = &c; if (a > b) swap(p1, p2); if (a > c) swap(p1, p3); if (b > c) swap(p2, p3); printf("%d %d %d \n", a,b,c); } } void swap(int *pt1, int *pt2) //實參和形參之間 “值傳遞” { int temp; temp = *pt1; *pt1 = *pt2; *pt2 = temp; } /*錯誤的的交換函式 函式 實參和形參之間的資料是單純的單向“值傳遞”,不能呼叫函式而改變實參變數的值 但是可以改變指定記憶體的值 */ void swap_wrong(int *pt1, int *pt2) //實參變數 { int *temp; temp = pt1; pt1 = pt2; pt2 = temp; }