如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
how to calculate the number of digits of an element inside of an array?(not the length of an array) and also calculate the sum of its digits
假设数组是a[]={1233453321123}。如何计算索引1处元素的长度?我知道我做错了,但我不知道如何处理这个
#include<iostream>
using namespace std;
int main()
{
int a[]={123,231,23},j=0,num,last_digit,sum;
int size_of_array=sizeof(a)/4;
int pos;
cin>>pos;
num=a[pos];
for(int i=0;i<size_of_array;i++)
{
last_digit=num%10;
sum=sum+last_digit;
num=num/10;
}
cout<<sum;
}
"我想计算我需要其长度的元素的位数之和">
令人困惑。如果你想把元素转换成字符串,然后计算它的长度,你可以这样做:
std::cout << "Length: " << std::to_string(a[i]).size() << std::endl;
其中i是数组a[]的索引。
然而,如果你想计算数字的总和,那么我想你正在尝试这样做:
int sumCell = 0;
int cellValue = a[i];
while(cellValue > 0) {
sumCell = cellValue % 10;
cellValue /= 10;
}
Sum在变量sumCell中。
你是在寻找这两种解决方案中的一种,还是另一种?
就像普通的int
#include<iostream>
int main() {
int a[]={123,231,23};
size_t pos; // use size_t for index and size
std::cin >> pos;
int elm = a[pos];
int cnt = 1;
while ( elm /= 10) {
++cnt;
}
std::cout << cnt << std::endl;
return 0;
}
输入索引并获取长度。
#include<iostream>
using namespace std;
int main()
{
int a[] = { 123, 231, 23 }, j = 0, num, last_digit, sum = 0, count = 0;
size_t size_of_array = sizeof(a) / 4;
size_t index;
cin >> index;
num = a[index];
while (num != 0) {
last_digit = num % 10;
sum = sum + last_digit;
num = num / 10;
count = count + 1;
}
cout << sum << endl; //sum
cout << count; //number of digits
}
相关文章:
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 通过指针算法计算数组长度
- 计算数组重复次数的组合的有效算法,加起来达到给定的总和
- 当我使用需要计算数组单元格地址的模板时,奇怪的C++行为
- 计算数组的特征值/向量,而不是使用特征 3 计算矩阵
- C++ 计算数组中的单词
- 计算数组行中的总和
- 计算数组中存在其总和的对数的算法
- 如何计算数组整数的总可能组合
- 使用 sizeof 计算数组中的元素数时的结果不同
- C :如何计算数组中唯一客户端的数量并输出其支出
- 以C++为单位计算数组中的重复数字
- 通过分而治算法计算数组的最大数量
- 我需要以尺寸方式计算数组的平均值
- 计算数组中特定线的平均值并存储在另一个数组中
- 如何在 c++ 中计算数组中的元素数量?
- 计算数组中"a"字母
- 避免在函数调用中计算数组元素
- 使用sizeof()计算数组大小
- 计算数组中唯一字符的函数