所以,到目前为止,我有这个。我试图在数组中找到两个最大的数字并返回它们。我在网上查了很多资源,其中大多数人说"通过参考电话"是要走的路。但我不知道如何使它与我的程序一起工作。例如,我在网上看到了这个例子:
void Calculate(int x, int y, int* prod, int* quot)
{
*prod = x*y;
*quot = x/y;
}
int x = 10,y = 2, prod, quot;
Calculate(x, y, &prod, ")
以上程序如何实际"返回"?如何将返回值打印到控制台?
#include "stdio.h"
void largest_two( int numbers[], int len, int *largest, int *next_largest){
int i, temp;
*largest = numbers[0];
*next_largest = numbers[1];
if(*largest < *next_largest){
temp = *next_largest;
*largest = *next_largest;
*next_largest = temp;
}
for (i=0; i<sizeof(numbers); i++) {
if(numbers[i]>= *largest){
*largest = numbers[i];
*next_largest = *largest;
}
else if ( numbers[i] > *next_largest){
*next_largest = numbers[i];
}
}
}
int main() {
int numbers[] = {3, 1, 2, 3, 6, 2, 8, 0, 0, 0};
int len = 3;
int largest, next_largest;
//==>??? printf("%d %d", largest_two(numbers, len, &largest, &next_largest));
}
答案 0 :(得分:0)
Sides'(您应该阅读它们上的教程/书),您的主要问题是您正在尝试打印返回类型为void
的函数的单个返回值,这意味着它根本不会回来。
您的代码:
int main() {
int numbers[] = {3, 1, 2, 3, 6, 2, 8, 0, 0, 0};
int len = 10; // sizeof(numbers)
int largest, next_largest;
largest_two(numbers, len, &largest, &next_largest);
printf("%d %d", largest, next_largest);
}
请记住,这仍然不完全正确,但它确实解决了打印数字的问题。
此外,传递len
意味着您不应该执行此操作for (i=0; i<sizeof(numbers); i++)
,而是for (i=0; i<len; i++)
答案 1 :(得分:0)
首先,这一行:
for (i=0; i<sizeof(numbers); i++)
不正确。你想要这样做:
for (i=0; i<len; i++)
应该作为largest_two()
传递给sizeof numbers/sizeof numbers[0]
,这是数组的实际长度。
我还建议从largest
设置next_largest
和INT_MIN
到<limits.h>
,然后从他们那里找到这些值。看起来你也遇到指针问题,最好只在需要时才使用它们。
这是一个简化您的方法的示例,它在数组的一个循环中找到最大和第二大的元素。它也只在需要时使用指针。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define ARRAYSIZE(x) (sizeof x/sizeof x[0])
void largest_two(int numbers[], size_t len, int *largest, int *next_largest);
int main(void) {
int numbers[] = {3, 1, 2, 3, 6, 2, 8, 0, 0, 0};
int largest, next_largest;
largest_two(numbers, ARRAYSIZE(numbers), &largest, &next_largest);
printf("largest = %d\nnext_largest = %d\n", largest, next_largest);
}
void largest_two(int numbers[], size_t len, int *largest, int *next_largest) {
int max, smax;
max = smax = INT_MIN;
for (size_t i = 0; i < len; i++) {
if (numbers[i] > max) {
smax = max;
max = numbers[i];
} else if (numbers[i] > smax && numbers[i] < max) {
smax = numbers[i];
}
}
*largest = max;
*next_largest = smax;
}
<强>输出:强>
largest = 8
next_largest = 6
第二个数据集:
int numbers[] = {3, 1, 6, 3, 6, 2, 8, 0, 8, 7};
<强>输出:强>
largest = 8
next_largest = 7