C++ 程序查找字符数组中 ASCII 值的总和

编写一个 C++ 程序,通过示例查找字符数组中 ASCII 值的总和。在此 C++ 代码中,我们允许用户输入一个字符数组,并使用 for 循环(for(i = 0; name[i] != ‘\0’; i++) )来迭代从 0 到字符数组长度的值。

在循环中,我们将 name 数组中每个字符的 ASCII 值加到 ASCII_Sum(ASCII_Sum = ASCII_Sum + name[i])。这里,cout << “\nThe ASCII Value of “<< name[i] << ” = ” << (int)name[i] 语句会打印字符数组的 ASCII 值。

#include<iostream>
using namespace std;

int main()
{
	int i, ASCII_Sum = 0;
	char name[20];
	
	cout << "Please Enter any Name you want  =  ";
	cin.getline(name, 20);
	
	for(i = 0; name[i] != '\0'; i++)
	{
		cout << "\nThe ASCII Value of "<< name[i] << " = " << (int)name[i];
		ASCII_Sum = ASCII_Sum + name[i];
	}
	
	cout << "\nThe Sum of All ASCII Value in a Given Array "<< name << " = " << ASCII_Sum;
		
 	return 0;
}
C++ Program to find Sum of ASCII values in a Character Array

C++ 程序使用 While 循环查找字符数组中 ASCII 值的总和

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
	int i = 0, ASCII_Sum = 0;
	char name[20];
	
	cout << "Please Enter any Name you want  =  ";
	cin.getline(name, 20);
	
	while(i < strlen(name))
	{
		cout << "\nThe ASCII Value of "<< name[i] << " = " << (int)name[i];
		ASCII_Sum = ASCII_Sum + name[i];
		i++;
	}
	
	cout << "\n\nThe Sum of All ASCII Value in a Given Array "<< name << " = " << ASCII_Sum;
		
 	return 0;
}
Please Enter any Name you want  =  hello

The ASCII Value of h = 104
The ASCII Value of e = 101
The ASCII Value of l = 108
The ASCII Value of l = 108
The ASCII Value of o = 111

The Sum of All ASCII Value in a Given Array hello = 532

这是另一个 C++ 示例,使用 While 循环计算字符数组中 ASCII 值的总和。

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
	int i, sum = 0;
	char name[20];
	
	cout << "Please Enter the Name  =  ";
	cin.getline(name, 20);
	
	while(name[i]!='\0')
	{
		cout << "\nThe ASCII Value of "<< name[i] << " = " << (int)name[i];
		sum = sum + name [i];
		i++;
	}
	cout << "\n\nThe Sum of all characters  = "<< sum;
		
 	return 0;
}
The ASCII Value of t = 116
The ASCII Value of u = 117
The ASCII Value of t = 116
The ASCII Value of o = 111
The ASCII Value of r = 114
The ASCII Value of i = 105
The ASCII Value of a = 97
The ASCII Value of l = 108
The ASCII Value of g = 103
The ASCII Value of a = 97
The ASCII Value of t = 116
The ASCII Value of e = 101
The ASCII Value of w = 119
The ASCII Value of a = 97
The ASCII Value of y = 121

The Sum of all characters  = 1638