四位正整数求各个位数和
时间: 2024-10-22 21:20:34 浏览: 32
要计算一个四位正整数(例如1234)的各位数字之和,你可以使用C++的`std::string`类型将整数转换为字符串,然后遍历每个字符,将其转换回整数并加总。以下是一个简单的示例代码:
```cpp
#include <iostream>
#include <sstream>
int sumOfDigits(int num) {
std::ostringstream oss; // 将整数转为字符串流
oss << num;
std::string str = oss.str(); // 获取字符串
int sum = 0;
for (char digit : str) {
if (isdigit(digit)) { // 检查是否为数字字符
sum += static_cast<int>(digit); // 转换为整数并累加
}
}
return sum;
}
int main() {
int fourDigitNum = 1234;
int digitsSum = sumOfDigits(fourDigitNum);
std::cout << "The sum of digits in the number " << fourDigitNum << " is " << digitsSum << "." << std::endl;
return 0;
}
```
在这个代码里,`sumOfDigits`函数接收一个四位数,`std::istringstream` `oss`被用来存储该数,然后通过遍历字符串中的每个字符,我们确保只对数字字符进行求和。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)