如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和

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

本文关键字:计算 数组 数字 何计算 元素      更新时间:2023-10-16

假设数组是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
}