[英]How do I modify this condition to accept another possibility?
Currently, I have this:目前,我有这个:
printf("%c", board[down][across] == 0 ? 'O' : 'X');
Which means - If the value at this position in the array is 0, display 'O', otherwise display 'X'这意味着 - 如果数组中此 position 处的值为 0,则显示“O”,否则显示“X”
How do I modify this so that:我该如何修改它,以便:
If the value at this position in the array is 0, display 'O', or if the value is 1 then display 'X' or if the value is 2 display '#'?如果数组中此 position 的值为 0,则显示“O”,或者如果值为 1,则显示“X”,或者如果值为 2,则显示“#”?
I understand I can just use if statements and use the printf line multiple times, but is there a better way of doing so, in one line, like above?我知道我可以只使用 if 语句并多次使用 printf 行,但是有没有更好的方法,在一行中,像上面一样?
Thanks.谢谢。
Make a function that takes the grid value and returns the char
.制作一个 function ,它采用网格值并返回
char
。
Ensure you handle unknown values as you must always return
something.确保您处理未知值,因为您必须始终
return
一些东西。
char get_char(int const grid_value)
{
switch (grid_value)
{
case 0:
return 'O';
case 1:
return 'X';
case 2:
return '#';
default:
return '?';
}
}
then just然后就
printf("%c", get_char(board[down][across]));
A straightforward way is to add an extra condition:一种直接的方法是添加一个额外的条件:
grid[down][across] == 0 ? 'O' : grid[down][across] == 1 ? 'X' : '#'
This is parsed as这被解析为
grid[down][across] == 0 ? 'O' : (grid[down][across] == 1 ? 'X' : '#')
So you'll get the desired result that 0 → O
, 1 → X
and everything else → #
.因此,您将获得 0 →
O
、 1 → X
和其他所有内容 → #
的预期结果。
Apparently it's going to be a mess if you want some more values (eg 3, 4, 5 and so on).显然,如果您想要更多的值(例如 3、4、5 等),这将是一团糟。 If you can make some assumption or guarantee about your values, like it will always be non-negative and bounded, you can use an array to hold your characters:
如果您可以对您的值做出一些假设或保证,例如它始终是非负的和有界的,您可以使用数组来保存您的字符:
const char LEGEND[] = {'O', 'X', '#'};
// ...
printf("%c", LEGEND[grid[down][across]]);
This has the advantage that you can easily add more values, for example:这样做的好处是您可以轻松添加更多值,例如:
const char LEGEND[] = {'O', 'X', '#', '!', '?', '.'};
but of course, it's never bad to check if the value is within the desired range before using it as array indices.但当然,在将其用作数组索引之前检查该值是否在所需范围内总是不错的。 So your code should be:
所以你的代码应该是:
int ind = grid[down][across];
// Assume you're using 3 characters
if (ind < 0 || ind >= 3) {
puts("Oops!");
exit(1);
}
printf("%c", LEGEND[ind]);
Create an array with possible values:创建一个包含可能值的数组:
char values[3] = {'O', 'X', '#'};
and then simply然后简单地
printf("%c", values[grid[down][across]]);
You can nest ternary operator.您可以嵌套三元运算符。
printf("%c", grid[down][across] == 0 ? 'O' : grid[down][across] == 1 ? 'X' : '#');
But sure don't use such that code in production!但千万不要在生产中使用这样的代码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.