我正在尝试编写一个 C 程序,该程序根据输入的数字计算最小值和最大值。我设法找到了最小值和最大值,但由于某种原因,我无法打印出函数之外的值。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
void find_largest_smallest(int a[], int n, int *largest, int *smallest)
{
largest=smallest=a[0];
int i;
for(i=0; i<n; i++)
{
if (largest<a[i])
largest=a[i];
}
for(i=0; i<n; i++)
{
//printf("%d\n", a[i]);
if (smallest>a[i])
smallest=a[i];
}
printf("Largest is %d\n", largest);
printf("smallest is %d\n", smallest);
}
int main()
{
int elem;
int i;
int *x;
int *y;
printf("How many elements you want to store ?:");
scanf("%d", &elem);
int store[elem];
for(i=0; i<elem; i++)
{
printf("Enter a value to be stored:");
scanf("%d", &store[i]);
}
find_largest_smallest(store, elem, &x, &y);
printf("Largest value stored is %d and the smallest is %d.", *x, y);
return 0;
}
这:
largest=smallest=a[0];
是错的。您正在为指针分配一个整数。你应该做的是:
*largest = a[0];
*smallest = a[0];
其他作业也是如此,内容如下:
if (*largest < a[i])
*largest = a[i];
/* ... */
if (*smallest > a[i])
*smallest = a[i];
/* ... */
printf("Largest is %d\n", *largest);
printf("smallest is %d\n", *smallest);
x
和y
in main的声明应该是int
(不是int *
):
int x, y;
调用printf
inmain
也是错误的:
printf("Largest value stored is %d and the smallest is %d.", x, y);
// no asterisk needed here ----------^
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句