
?:
General Comments
This operator takes three operands, each of which is an expression.
They are arranged as follows:
expression1 ? expression2 : expression3
The value of the whole expression equals the value of expression2
if expression1 is true. Otherwise, it equals the value of
expression3.
(5 > 3) ? 1 : 2 has the value 1.
(3 > 5) ? 1 : 2 has the value 2.
(a > b) ? a : b has the value of the larger of a or b.
Example
Code
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void main()
{
const float MIN = 0.0f;
const float MAX = 100.0f;
float score;
float total = 0.0f;
int n = 0;
float min = MAX;
float max = MIN;
printf("Enter the first score (q to quit):");
while (scanf("%f", &score) == 1)
{
if (score<MIN || score>MAX)
{
printf("%0.1f is an invalid value. Try again:",score);
continue;
}
printf("Accepting %0.1f:\n", score);
min = (score < min) ? score : min;
max = (score > max) ? score : max;
total += score;
n++;
printf("Enter next score (q to quit):");
}
if (n > 0)
{
printf("Average of %d scores is %0.1f.\n", n, total / n);
printf("Low = %0.1f, high = %0.1f\n", min, max);
}
else
printf("No valid scores were entered.\n");
getchar();
getchar();
getchar();
}
Output
