任务是从用户获取5个整数的输入并使用#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);
}
这是我的程序代码。任何解释或帮助将不胜感激!
搜索最大值的搜索可以如下即时完成;宏和程序本身都不需要一个数组。
#include <stdio.h>
#include <limits.h>
#define LARGEST(x,y) ( (x) > (y) ? (x) : (y) )
int main()
{
int a = INT_MIN;
int i = 0;
for(i=0; i<5; i++)
{
int x = 0;
printf("Enter the value of X:n");
scanf("%d", &x);
a = LARGEST(x, a);
}
printf("%d", a);
}
宏使用三元操作员对其较大的参数进行评估。在程序本身中,仅使用当前输入和当前最大值的局部变量。最大值以最小的值初始化。
继续从注释中继续,您可以每次获取最大的输入,也可以将所有输入存储在数组中,然后在数组中循环循环。第一种方法要简单得多:
#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: %dn", largest);
return 0;
}
看事物,让我知道您是否有任何疑问。