【发布时间】:2018-06-06 04:41:42
【问题描述】:
我必须编写一个应用程序,用户在其中给出数字数组的长度以及数组元素之和将转换为的基数。然后用户给出一个数组。应用程序必须对给定元素求和,然后将总和转换为给定的基数并计算总和的位数。更重要的是,它还应该打印输入了多少位数字。 例如一个
input is:
3 10 // 3 - length, 10 - base
1 2 3 // array
And the output:
1 // number of digits of the sum in base 10
6 // number of digits in input
另一个例子:
Input:
3 2
1 2 3
Output:
3
5
到目前为止我所写的:
#include <iostream>
using namespace std;
void convert(int N, int b)
{
//int result = 0;
if (N == 0)
return ;
int x = N % b;
N /= b;
if (x < 0)
N += 1;
convert(N, b);
cout << (x < 0 ? x + (b * -1) : x);
return;
}
int countDigits(int number) {
if (number < 10) {
return 1;
}
int count = 0;
while (number > 0) {
number /= 10;
count++;
}
return count;
}
int main()
{
int n, d;
cin >> n >> d;
int a;
long long int sum = 0;
int count = 0;
while (count++ < n) {
cin >> a;
sum += a;
}
cout << "Sum: " << sum << endl << "Diff Base: ";
if (sum != 0)
{
convert(sum, d);
cout << endl;
}
else
cout << "0" << endl;
return 0;
}
问题是我不知道如何将 convert 函数更改为 int,所以我可以轻松地将 return 传递给 countDigits 函数。而且我不知道如何计算输入数字。它应该尽可能高效。
【问题讨论】:
-
也许你能解释更多?尤其是每个输出的计算方式。
-
嗯,首先我计算数组的总和。总和计入主要。然后我使用函数转换,将总和转换为给定的基数。问题是我的函数 convert 是 void 类型,所以我不能将结果传递给函数 countDigits。因为如果可以的话,我将完成第一个输出:求和 -> 转换为基数 -> 计算数字。