如何使用 C 将具有 2 个变量的 IF 语句转换为 switch 函数? [英] How do I transform an IF statement with 2 variables onto a switch function using C?
本文介绍了如何使用 C 将具有 2 个变量的 IF 语句转换为 switch 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 IF 语句,我想将它转换为一个 Switch 语句......但它有 2 个变量!是否可以在 C 上完成?
I have an IF-statement that I want to transform into a Switch-statement... But it has 2 variables! Is it possible to do it on C?
这是一个石头、纸、剪刀的游戏:
It is a rock, paper, scissors game:
(R代表石头,P代表纸,S代表剪刀)
(R for rock, P for Paper, S for Scissors)
char play1, play2;
printf("
Player 1 - Enter your Play: ");
scanf ("%c", &play1);
printf("
Player 2 - Enter your Play: ");
scanf (" %c", &play2);
if (play1 == 'R' && play2 == 'P') {
printf ("Paper wins!"); }
else if (play1 == 'R' && play2 == 'S') {
printf ("Rock wins!");}
else if (play1 == 'R' && play2 == 'R) {
printf ("Draw!");}
而且我必须为其他选项这样做,所以最好使用 switch!
and I have to do this for the others options, so it would be better to use switch!
推荐答案
#include <stdio.h>
#define SWITCH(a, b) char _a = a; char _b = b; if (0)
#define CASE(a, b) } else if ((a == _a) && (b == _b)) {
int main(void)
{
char play1, play2;
printf("
Player 1 - Enter your Play:");
scanf ("%c", &play1);
getchar();
printf("
Player 2 - Enter your Play:");
scanf ("%c", &play2);
getchar();
SWITCH(play1, play2) {
CASE('R','P') printf ("Paper wins!");
CASE('R','S') printf ("Rock wins!");
CASE('R','R') printf ("Draw!");
}
return 0;
}
这是个笑话:P
:"的大小写支持
#define PASTE(a, b) a##b
#define LABEL(a, b) PASTE(a, b)
#define SWITCH(a, b) char _a = a; char _b = b; if (0)
#define CASE(a, b) } else if ((a == _a) && (b == _b)) { LABEL(LBL, __LINE__)
但不适用于:
CASE('R','R'): printf ("Draw a!"); CASE('S','R'): printf ("Draw!");
两个case在同一行
解决方法:
#define SWITCH(a, b) char _a = a; char _b = b; if (0)
#define CASE(a, b) } else if ((a == _a) && (b == _b)) {switch(1) case 1
希望没有人使用它:)
这篇关于如何使用 C 将具有 2 个变量的 IF 语句转换为 switch 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文