C++ 找到出现在素数位置的字符的ASCII值的总和
介绍
在本教程中,我们将学习C++的概念,即计算出现在素数位置的字符的ASCII值的总和。素数位置指的是位置为2、3、5或其他素数的字符。
ASCII(美国标准信息交换代码)值是用于编码的字母、字母、标点符号和其他字符的唯一数字值。它用于与计算机进行通信,因为计算机无法理解人类语言。
ASCII值从0到127的范围内有128个值。大写和小写字母有不同的ASCII值。
我们将开发一个C++代码来计算位于素数位置的字符的ASCII值。我们使用了字符串类的length()函数来存储输入字符串的长度。
示例1
There is an string = “Hello”
Sum of prime position ASCII value characters = 320
In the above string “Hello” the ASCII value of each character is
H = 72
e = 101
l = 108
l = 108
o = 111
在原位置的字符是“e”,“l”,“o”。将这些原位置字符的ASCII值相加。
示例2
Input string = “abcd”
Sum = 197
输入字符串“abcd”的主要位置字符是“b”和“c”。
The ASCII value of input string characters is as listed:
a = 97
b = 98
c = 99
d = 100
计算字符串中位于质数位置的字符的ASCII值之和。
语法
- sqrt() - 该库函数定义在math库中,它返回输入数字的平方根。
sqrt(n)
- length() − 这个字符串类库函数返回输入字符串的长度,长度是字符串中的字符数。
string_name.length();
示例1
我们将使用 C++ 编程语言实现一个示例,来计算输入字符串中位于素数位置的字符的 ASCII 值之和。C++ 代码输入字符串为“Hello”。我们首先通过应用识别素数的逻辑找到输入字符串的所有素数位置。使用 for 循环找到输入字符串所有字符的 ASCII 值。将位于素数位置的字符串字符的 ASCII 值求和。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// User-defined function to find the prime positions
bool find_prime(int p){
if (p <= 1) {
return false;
}
// loop to check the prime number
for (int x = 2; x*x <= p; x++) {
if (p % x == 0) {
return false;
}
}
return true;
}
// user-defined function to sum ASCII values of the prime position characters
int sum_of_primes(string st) {
int sum1 = 0;
//variable to store the input string length.
int p = st.length();
vector<bool> primes(p+1, false);
primes[2] = true;
for (int x = 3; x <= p; x += 2) {
primes[x] = find_prime(x);
}
for (int x = 2; x <= p; x++){
if (primes[x] && x <= p){
sum1 += int(st[x-1]);
}
}
return sum1;
}
// controlling code
int main(){
string st = "Hello";
int sum1 = sum_of_primes(st);
cout << "Sum of ASCII values of characters at prime positions: " << sum1 << endl;
return 0;
}
输出
"Sum of ASCII values of characters at prime positions: 320
示例2
在这里,我们使用了不同的逻辑来实现示例。我们首先找到质数的位置,在main()函数中找到它们的ASCII值并进行相加。
#include <iostream>
#include <cmath>
using namespace std;
bool isNumPrime(int n) {
if (n < 2)
return false;
for (int x = 2; x <= sqrt(n); ++x) {
if (n % x == 0)
return false;
}
return true;
}
int main() {
string str = "tutorialspoint";
//std::cout << "Enter a string: ";
int s = 0;
for (size_t x = 0; x < str.length(); ++x) {
if (isNumPrime(x + 1)) {
s += static_cast<int>(str[x]);
}
}
cout << "Sum of ASCII values at prime positions: " << s << endl;
return 0;
}
输出
Sum of ASCII values at prime position: 665
结论
在本教程中,我们开发了C++代码,用于找到在素数位置字符的ASCII值的总和。我们使用了string类的length()函数来找到参数字符串的长度。ASCII值是字母和其他字符的预定值,用于帮助计算机进行通信。在本教程中,我们实现了两个具有不同逻辑的示例,并使用了一些C++库函数。最重要的库函数是length()。这个length()库函数返回字符串的长度。