问题描述
我必须编写一个比较3个整数的程序。我不明白为什么我不能将变量a分配给最小或最大变量。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c,max,notmax;
printf("enter first integer\n");
scanf("%d",&a);
printf("enter second integer\n");
scanf("%d",&b);
printf("enter third integer\n");
scanf("%d",&c);
a > b ? a = max : a = notmax ;
return 0;
}
解决方法
了解优先级和关联性可能会帮助您了解此处发生的情况。分配的优先级比?:运算符低。 所以声明
a > b ? a = max : a = notmax ;
被视为:
((({a > b ? a = max : a) = notmax );
但是一旦您在适当的位置使用了括号,如下所示,一切正常:
a > b ? a = max : (a = notmax) ;
或者甚至是类似的东西
(a> b ? (a = max) : (a = notmax)) ;
应按您想要的方式强制优先。使用括号将有助于评估复合语句。
,可接受的答案说明您看到的错误是由于?:
和=
之间的运算符优先级引起的。它没有提到的是最好的解决方法。
?:
运算符的计算结果为第二部分或第三部分的值。因此,它可以用于选择max
或notmax
并将其分配给a
。
a = a > b ? max : notmax;
但是,您的代码 still 存在问题,因为max
和notmax
尚未初始化,因此它们的值不确定并读取它们可能导致undefined behavior。在运行此状态之前,您需要确保为这两个变量都分配了一个值。