任务是从用户那里获取5个整数的输入并使用#define
指令,找到最大值。现在,我已经使用define指令来定义常量,甚至更小的函数,但无法理解这背后的逻辑。我应该在#define
?
#include <stdio.h>
#define LARGEST(y) ((y[0]>y[1])?y[0]:y[1])
int main()
{
int i,y;
int x[5];
for(i=0;i<5;i++){
printf("Enter the value of X:\n");
scanf("%d", &x[i]);}
int a=LARGEST(x);
printf("%d", a);
}
这是我的程序代码。任何解释或帮助将不胜感激!
答案 0 :(得分:0)
最大限度的搜索可以如下进行;宏和程序本身都不需要一个数组。
{{1}}
宏使用三元运算符来评估其中较大的参数。在程序本身中,仅使用当前输入的局部变量和当前最大值;最大值被初始化为可能的最小值。
答案 1 :(得分:0)
继续注释,您可以在每次输入时检查最大值,或者可以将所有输入存储在数组中,然后循环遍历数组中的每个值。第一种方法更简单:
#include <stdio.h>
#define MAX 5
#define LARGEST(a,b) ((a) > (b) ? (a) : (b))
int main (void)
{
int largest = 0, n = 0, x;
while (n < MAX) {
int ret;
printf ("enter value %d of %d: ", n + 1, MAX);
ret = scanf ("%d", &x); /* validate conversion */
if (ret == 1) { /* input is valid */
if (n) /* not the first value */
largest = LARGEST(largest,x);
n++;
}
else if (ret == EOF) { /* always check EOF */
fprintf (stderr, "user canceled input.\n");
return 0;
}
else { /* input was not an integer */
fprintf (stderr, "error: invalid input.\n");
int c; /* flush stdin to avoid loop */
while ((c = getchar()) != '\n' && c != EOF) {}
}
}
printf ("\nlargest: %d\n", largest);
return 0;
}
仔细看看,如果您有任何问题,请告诉我。