有一堆正整数,统计其中有多少立方数c++
时间: 2024-03-03 14:52:58 浏览: 27
可以使用以下代码来统计一堆正整数中有多少个立方数:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int countCubeNumber(int arr[], int n) {
int count = 0;
for(int i = 0; i < n; i++) {
int cubeRoot = round(cbrt(arr[i])); // 求立方根并四舍五入
if(cubeRoot * cubeRoot * cubeRoot == arr[i]) { // 判断是否为立方数
count++;
}
}
return count;
}
int main() {
int arr[] = {1, 8, 27, 64, 125, 216}; // 示例数组
int n = sizeof(arr) / sizeof(arr[0]);
int count = countCubeNumber(arr, n);
cout << "该数组中有 " << count << " 个立方数" << endl;
return 0;
}
```
该代码遍历一遍数组,对于每个数,先求出它的立方根并四舍五入,然后判断该数是否等于该立方根的立方,如果是,则说明该数是一个立方数。最后统计立方数的个数并返回。
相关问题
输入一行字符串统计其中有多少个整数
输入一行字符串,统计其中有多少个整数可以通过以下步骤实现:
1. 定义一个空列表a,用于存放提取出来的整数。
2. 遍历字符串中的每一个字符,判断是否为数字,如果是数字则将其加入一个临时字符串temp中。
3. 如果当前字符不是数字,且临时字符串temp不为空,则将其转换为整数并加入列表a中,并清空临时字符串temp。
4. 遍历完整个字符串后,如果临时字符串temp不为空,则将其转换为整数并加入列表a中。
5. 输出列表a中的所有整数,并统计其个数。
代码如下(Python):
```python
s = input() # 输入字符串
a = [] # 存放整数的列表
temp = '' # 临时字符串
for c in s:
if c.isdigit(): # 如果是数字则加入临时字符串
temp += c
elif temp: # 如果不是数字且临时字符串不为空,则将其转换为整数并加入列表a中
a.append(int(temp))
temp = ''
if temp: # 遍历完字符串后,如果临时字符串不为空,则将其转换为整数并加入列表a中
a.append(int(temp))
print('共有%d个整数,别为:%s' % (len(a), a)) # 输出整数个数和列表a中的所有整数
```
统计正整数指定数字的个数c++
以下是统计正整数指定数字的个数的C++代码实现:
```c++
#include <iostream>
using namespace std;
int count(int n, int num) {
int cnt = 0;
while (n) {
if (n % 10 == num) {
cnt++;
}
n /= 10;
}
return cnt;
}
int main() {
int n, num;
cout << "请输入一个正整数n和指定数字num:" << endl;
cin >> n >> num;
int ans = 0;
for (int i = 1; i <= n; i++) {
ans += count(i, num);
}
cout << "在1~" << n << "中,数字" << num << "出现的次数为:" << ans << endl;
return 0;
}
```
该程序首先通过 `count` 函数统计一个数的十进制表示中指定数字出现的次数,然后在主函数中对1~n中每个数调用 `count` 函数,最后统计出数字num在1~n中出现的总次数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)