所以我試着做一個代碼:主要得到輸入三個數字,然後把這些數字的指針發送到需要在它們之間交換的函數,直到我們有我們想要的。我們希望在代碼\函數的最後,最大的數字將在num1中,第二大的數字將在num2中,最小的數字將在num3中。請幫助我的指針。該函數打印一些垃圾值。指針代碼
#include <stdio.h>
#include <stdlib.h>
void whichIsBigger(int* num1, int* num2, int* num3);
void swap(int* num1, int* num2);
void printsAnswer(int* num1, int* num2, int* num3);
int main(void)
{
int num1, num2, num3;
int* pnum1 = &num1;
int* pnum2 = &num2;
int* pnum3 = &num3;
printf("Please enter three number\n");
scanf("%d %d %d",&num1,&num2,&num3);
whichIsBigger(pnum1, pnum2, pnum3);
system("PAUSE");
return 0;
}
/*
*/
void whichIsBigger(int* num1, int* num2, int* num3)
{
if ((*num3 > *num1) && (*num3 > *num2))
{
if (*num1 > *num2)
{
swap(&num1, &num2);
}
}
else if ((*num2>*num1) && (*num2>*num3))
{
swap(&num2, &num3);
if (*num1 > *num2)
{
swap(&num1, &num2);
}
}
else if ((*num1 > *num2) && (*num1 > *num3))
{
swap(&num1, &num3);
if (*num1 > *num2)
{
swap(&num1, &num2);
}
}
printsAnswer(&num1, &num2, &num3);
}
/*
*/
void swap(int* num1, int* num2)
{
int temp = *num1;
*num1 = *num2;
*num2 = temp;
}
/*
*/
void printsAnswer(int* num1, int* num2, int* num3)
{
printf("the biggest number is: %d\n", *num1);
printf("the second biggest number is: %d\n", *num2);
printf("the smallest number is: %d\n", *num3);
}
試着編譯它,並打開警告,你會學到一些有價值的東西:)例如'gcc -Wall your_file.c'主要問題是你傳遞指針而不是指針。 – jpw
爲什麼使用swap作爲交換(&num1,&num2)而不交換(num1,num2)?它已經是一個指針 – ItayB
在一邊注意whichIsBigger函數似乎給出了相反的結果(顯示最小的數字最大等) – jpw