不使用条件语句打印“偶数”或“奇数”

编写一个程序,接受用户输入的数字,如果输入的数字是偶数,则打印“偶数”,如果输入的数字是奇数,则打印“奇数”。不允许使用任何比较(=、、…等)或条件语句(if、else、switch、三元运算符等)。

null

方法1 下面是一个棘手的代码,可以用来打印“偶数”或“奇数”相应。

C++

#include <iostream>
using namespace std;
int main()
{
char arr[2][5] = { "Even" , "Odd" };
int no;
cout << "Enter a number: " ;
cin >> no;
cout << arr[no % 2];
getchar ();
return 0;
}


JAVA

import java.util.Scanner;
class GFG
{
public static void main(String[] args)
{
String[] arr = { "Even" , "Odd" };
Scanner s = new Scanner(System.in);
System.out.print( "Enter the number: " );
int no = s.nextInt();
System.out.println(arr[no% 2 ]);
}
}
// This code is contributed by divyeshrabadiya07.


蟒蛇3

arr = [ "Even" , "Odd" ]
print ( "Enter the number" )
no = int ( input ())
print (arr[no % 2 ])


C#

using System;
class GFG {
static void Main() {
string [] arr = { "Even" , "Odd" };
Console.Write( "Enter the number: " );
string val;
val = Console.ReadLine();
int no = Convert.ToInt32(val);
Console.WriteLine(arr[no%2]);
}
}
// This code is contributed by divyesh072019.


PHP

<?php
$arr = [ "Even" , "Odd" ];
$input = 5;
echo ( $arr [ $input % 2]);
// This code is contributed
// by Aman ojha
?>


Javascript

<script>
let arr = [ "Even" , "Odd" ];
let no = prompt( "Enter a number: " );
document.write(arr[no % 2]);
// This code is contributed by suresh07
</script>


方法2 下面是另一个棘手的代码,可以用来相应地打印“偶数”或“奇数”。幸亏 大学生 感谢你提出这种方法。

C++

#include<stdio.h>
int main()
{
int no;
printf ( "Enter a no: " );
scanf ( "%d" , &no);
(no & 1 && printf ( "odd" ))|| printf ( "even" );
return 0;
}


输出

Enter a no: even

如果你发现上面的代码不正确,请写评论,或者找到更好的方法来解决同样的问题

方法3 这也可以通过一个叫做 无分支编程。 本质上,利用Python(其他语言)中的true语句的计算结果为1,false语句的计算结果为false这一事实。

蟒蛇3

# code
n = int ( input ( "Enter a number: " ))
print ( "Even" * (n % 2 = = 0 ), "Odd" * (n % 2 ! = 0 ))


输出

Enter a number: Even 

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享