给定一个字符,我们需要在C / C++ / Java/ Python打印其ASCII值。
例子 :
Input : a
Output : 97
Input : D
Output : 68
以下是几种使用不同编程语言来打印给定字符的ASCII值的方法:
- 使用ord函数的Python代码:
ord():它将隐藏给定长度为1的字符串,返回一个表示该字符的Unicode代码点的整数。例如,ord(’a’)返回整数97。# Python program to print # ASCII Value of Character # In c we can assign different # characters of which we want ASCII value c = 'g' # print the ASCII value of assigned character in c print("The ASCII value of '" + c + "' is", ord(c))
输出:
The ASCII value of g is 103
- C代码:我们在这里使用格式说明符来给出字符的数值。这里, %d用于将字符转换为其ASCII值。
// C program to print // ASCII Value of Character #include
int main() { char c = 'k'; // %d displays the integer value of a character // %c displays the actual character printf("The ASCII value of %c is %d", c, c); return 0; } 输出:
The ASCII value of k is 107
- C++代码:这里的int()用于将字符转换为其ASCII值。
// CPP program to print // ASCII Value of Character #include
using namespace std; int main() { char c = 'A'; cout << "The ASCII value of " << c << " is " << int(c); return 0; } 输出:
The ASCII value of A is 65
- Java代码:在这里,要查找c的ASCII值,我们只需将c分配给一个int变量ascii。在内部, Java将字符值转换为ASCII值。
// Java program to print // ASCII Value of Character public class AsciiValue { public static void main(String[] args) { char c = 'e'; int ascii = c; System.out.println("The ASCII value of " + c + " is: " + ascii); } }
- C#代码:在这里,要查找c的ASCII值,我们只需将c分配给一个int变量ascii。在内部,C#将字符值转换为ASCII值。
// C# program to print // ASCII Value of Character using System; public class AsciiValue { public static void Main() { char c = 'e'; int ascii = c; Console.Write("The ASCII value of " + c + " is: " + ascii); } } // This code is contributed // by nitin mittal
输出:
The ASCII value of e is 101
想要从精选的最佳视频中学习和练习问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。