可惜不是你,陪我到最后
问题又来了哦
输入3个非负数,如果是2奇1偶则输出YES,否则输出NO.(用条件语句,不能用IF语句).
上面是我在一个论坛看到的求助帖子,我分别用C语言和JAVA做了解答,用位运算做了奇偶数校验,但是还是用了IF(虽然C用的是(?:)但和IF也一样),大家看看不用IF如何做?
下面是我的代码,编译通过,结果正确。
用C写的:
main()
{
int a,b,c,d;
printf("Please intput 3 int num ,like this 1,2,3\n");
scanf("%d,%d,%d",&a,&b,&c);
((a|b)%2==0?(d=0):((a&b)%2==0?(c%2==0?(d=0):(d=1)):(c%2==0?(d=1):(d=0))));
switch(d)
{
case 0:printf("NO");break;
case 1:printf("YES");break;
}
getch();
}
用JAVA的GUI程序。
import java.awt.*;
import java.awt.event.*;
class Jioushu extends Frame implements ActionListener
{
TextField t1 = new TextField(5);
TextField t2 = new TextField(5);
TextField t3 = new TextField(5);
TextField t4 = new TextField(5);
Label L1 = new Label("校验结果为");
Button btn = new Button("校验");
public Jioushu()
{
setLayout(new FlowLayout());
add(t1);
add(t2);
add(t3);
add(L1);
add(t4);
add(btn);
btn.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
int a,b,c,d;
try
{
a = Integer.parseInt(t1.getText());
b = Integer.parseInt(t2.getText());
c = Integer.parseInt(t3.getText());
if((a|b)%2==0)
{
d=0;
}
else
{
if((a&b)%2==0)
{
if(c%2==0)
{
d=0;
}
else
{
d=1;
}
}
else
{
if(c%2==0)
{
d=1;
}
else
{
d=0;
}
}
}
switch(d)
{
case 0:t4.setText("NO");break;
case 1:t4.setText("YES");;break;
}
}
catch(Exception ee)
{
t4.setText("数据输入错误!数字超出范围或者类型不正确!");
}
}
public static void main (String args[])
{
Jioushu mainFrame = new Jioushu();
mainFrame.setSize(500,150);
mainFrame.setTitle("奇偶数校验器");
mainFrame.setVisible(true);
}
}