gpt4 book ai didi

C 指针、最小值和最大值

转载 作者:行者123 更新时间:2023-11-30 18:54:59 25 4
gpt4 key购买 nike

我需要编写一个获取 num1、num2 和 num3 作为参数的函数。函数运行完成后,发送到主函数的参数(num1、num2 和 num3)应更改,以便 num1 包含最小值,num2 包含第二大值,num3 包含最大值。我还需要编写一个交换函数并使用它。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
void SmallBig(int* num1, int* num2, int* num3);
void swap(int* x, int* y);
void main()
{
int *num1, *num2, *num3;
*num1 = 1;
*num2 = 69;
*num3 = 22;
printf("%d %d %d\n", *num1, *num2, *num3);
SmallBig(*num1, *num2, *num3);
printf("%d %d %d\n", num1, num2, num3);
system("PAUSE");

}
void SmallBig(int* num1, int* num2, int* num3)
{
if (*num1 > *num3 && *num2 > *num3 && *num1 > *num2)
{
swap(num1, num3);
swap(num2, num2);
swap(num3, num1);
}
}
void swap(int* x, int* y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

这些是我得到的错误:

Warning 1   warning C4047: 'function' : 'int *' differs in levels of indirection from 'int' 
Warning 2 warning C4024: 'SmallBig' : different types for formal and actual parameter 1
Warning 3 warning C4024: 'SmallBig' : different types for formal and actual parameter 2
Warning 4 warning C4024: 'SmallBig' : different types for formal and actual parameter 3
Error 5 error C4700: uninitialized local variable 'num1' used
Error 6 error C4700: uninitialized local variable 'num2' used

错误 7 错误 C4700:使用了未初始化的局部变量“num3”

请帮我修复程序!谢谢。 - 阿姆农。

最佳答案

错误和问题

关于您的错误:

int *num1, *num2, *num3;  // you define 3 pointers to int but let them unitinialised !
*num1 = 1; // you write something to the poinded adress, which might be random !!
*num2 = 69;
*num3 = 22;

当您使用指针而不初始化它们时(您只初始化指向的值),您会收到此错误消息

然后你的第二个printf()打印指针而不是指向的值。

最后,SmallBig() 仅在少数情况下有效!

解决方案

main()中使用整数,而不是指针:

int num1, num2, num3;
num1 = 1;
num2 = 69;
num3 = 22;
printf("%d %d %d\n", num1, num2, num3);
SmallBig(&num1, &num2, &num3); // use the address
printf("%d %d %d\n", num1, num2, num3);

我差点忘了你的SmallBig()函数!在那里,继续像您一样使用指针。但你必须预见更多的情况:

   if (*num1 > *num3) 
swap (num1, num3);
if (*num1 > *num2)
swap (num1, num2);
if (*num2 > *num3)
swap(num2, num3);

关于C 指针、最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29188723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com