Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;快速基数转换、数字计数_C++_Count_Converter_Base - Fatal编程技术网

C++ C++;快速基数转换、数字计数

C++ C++;快速基数转换、数字计数,c++,count,converter,base,C++,Count,Converter,Base,我必须编写一个应用程序,用户在其中给出数字数组的长度以及数组元素总和转换为的基数。然后用户给出一个数组。应用程序必须对给定的元素求和,然后将和转换为给定的基数,并计算和的位数。更重要的是,它还应该打印作为输入给出的数字数量。 比如说 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

我必须编写一个应用程序,用户在其中给出数字数组的长度以及数组元素总和转换为的基数。然后用户给出一个数组。应用程序必须对给定的元素求和,然后将和转换为给定的基数,并计算和的位数。更重要的是,它还应该打印作为输入给出的数字数量。 比如说

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;
#包括
使用名称空间std;
无效转换(整数N,整数b)
{
//int结果=0;
如果(N==0)
回来
int x=N%b;
N/=b;
if(x<0)
N+=1;
转换(N,b);
cout(0){
数目/=10;
计数++;
}
返回计数;
}

intmain()
{
int n,d;
cin>>n>>d;
INTA;
长整型和=0;
整数计数=0;
while(count++>a;
总和+=a;
}

cout我相信你需要一个函数,它只需执行:求和->指定基数的数字。你将很难用一个未指定的基数表示你的和,然后计算它的数字。下面的函数应该涵盖广泛的基数

int nr_digits_in_base(long long int N, int B)
{
    assert(B > 1);
    int nr_digits_to_represent_N_in_base_B = N < 0 ? 2 : 1;
    while (N /= B)
        nr_digits_to_represent_N_in_base_B++;
    return nr_digits_to_represent_N_in_base_B;
}
int-nr\u数字\u在\u基(long-long-int-N,int-B)
{
断言(B>1);
int nr_数字_至_表示_基中的_N_=N<0?2:1;
while(N/=B)
nr_数字_至_表示_base_B++中的_N_;
返回N个数字到表示基中的N;
}

或者,有一种方法是使用对数在固定时间内计算答案。

也许你可以解释更多?尤其是如何计算每个输出。首先,我计算数组的和。和在主数组中计算。然后我使用函数转换,将和转换为给定的基。问题是,我的函数转换是void类型e、 所以我无法将结果传递给countDigits函数,因为如果可以,我将完成第一个输出:sum->convert to base->count the digits。
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;
int nr_digits_in_base(long long int N, int B)
{
    assert(B > 1);
    int nr_digits_to_represent_N_in_base_B = N < 0 ? 2 : 1;
    while (N /= B)
        nr_digits_to_represent_N_in_base_B++;
    return nr_digits_to_represent_N_in_base_B;
}