整数数组中每个元素的数字总和
Sum of digits of each elements inside an array of integers
我想计算数组中每个元素的数字总和。问题是这段代码只计算数组中奇数索引 (1,3,5...) 的总和。在控制台中,它显示偶数索引的一些随机数 (0,2,4...)
谁能告诉我这是什么问题?
是的,我需要将它用作数组
这里是输出值:
Enter how many numbers you want to calculate sum of digits: 5
Enter those numbers: 12
Enter those numbers: 33
Enter those numbers: 44
Enter those numbers: 22
Enter those numbers: 33
Sum of 0 number is: 4
Sum of 1 number is: 6
Sum of 2 number is: 40
Sum of 3 number is: 4
Sum of 4 number is: 11730950
#include <iostream>
int main(int argc, char** argv)
{
int n;
int temp;
int pom;
cout << "Enter how many numbers you want to calculate sum of digits: ";
cin >> n;
int numbers[n];
int sum[n];
for (int i = 0; i < n; i++)
{
cout << "Enter those numbers: ";
cin >> numbers[i];
}
for (int i = 0; i < n; i++)
{
while (numbers[i] > 0)
{
temp = numbers[i] % 10;
sum[i]+= temp;
numbers[i] = numbers[i]/10;
}
}
for (int i = 0; i < n; i++)
{
cout << "Sum of " << i << " number is: " << sum[i] << endl;
}
return 0;
}
您需要初始化 sum
数组,如下所示:
int sum[n] {};
否则,当您第一次读取 sum
的元素时,您有未定义的行为。
此外,可变长度数组不是标准 c++ 的一部分。如果在编译时不知道数组的大小,只需使用 std::vector
.
如果您绝对必须使用数组,那么您将需要动态分配它,如下所示:
int * arr = new int[n]{};
我想计算数组中每个元素的数字总和。问题是这段代码只计算数组中奇数索引 (1,3,5...) 的总和。在控制台中,它显示偶数索引的一些随机数 (0,2,4...)
谁能告诉我这是什么问题?
是的,我需要将它用作数组
这里是输出值:
Enter how many numbers you want to calculate sum of digits: 5
Enter those numbers: 12
Enter those numbers: 33
Enter those numbers: 44
Enter those numbers: 22
Enter those numbers: 33
Sum of 0 number is: 4
Sum of 1 number is: 6
Sum of 2 number is: 40
Sum of 3 number is: 4
Sum of 4 number is: 11730950
#include <iostream>
int main(int argc, char** argv)
{
int n;
int temp;
int pom;
cout << "Enter how many numbers you want to calculate sum of digits: ";
cin >> n;
int numbers[n];
int sum[n];
for (int i = 0; i < n; i++)
{
cout << "Enter those numbers: ";
cin >> numbers[i];
}
for (int i = 0; i < n; i++)
{
while (numbers[i] > 0)
{
temp = numbers[i] % 10;
sum[i]+= temp;
numbers[i] = numbers[i]/10;
}
}
for (int i = 0; i < n; i++)
{
cout << "Sum of " << i << " number is: " << sum[i] << endl;
}
return 0;
}
您需要初始化 sum
数组,如下所示:
int sum[n] {};
否则,当您第一次读取 sum
的元素时,您有未定义的行为。
此外,可变长度数组不是标准 c++ 的一部分。如果在编译时不知道数组的大小,只需使用 std::vector
.
如果您绝对必须使用数组,那么您将需要动态分配它,如下所示:
int * arr = new int[n]{};