c++代码在编译器中不运行产品函数

6yjfywim  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(99)

我应该怎么做产品功能没有运行在编译器中的一些数字,如a=511和b= 512也和功能没有运行请帮助我调试它,我需要你的帮助,期待它给我,我是学生,我正在学习c++感谢这段代码使两个十进制数到二进制和总和,并乘以他们

#include <iostream>
#include <cmath>
using namespace std;

int* binary(int, int);
int* sum(int[], int[], int, int);
int* product(int[], int[], int, int);
void display(int[], int);

int main()
{
    int x, y;
    cout << "Enter two decimal numbers:\n";
    cin >> x >> y;

    int t = log2(x) + 1;
    int* a = binary(x, t);
    cout << "Binary: ";
    display(a, t);

    int u = log2(y) + 1;
    int* b = binary(y, u);
    cout << "\nBinary: ";
    display(b, u);

    int* c = sum(a, b, t, u);
    cout << "\nSum: ";
    int z = t;
    if (u > t)
        z = u;
    display(c, z + 1);

    int* d = product(a, b, t, u);
    cout << "\nProduct: ";
    cout << d[0] << d[1] << d[2];
    display(d, t + u);
}

int* binary(int x, int t)
{
    int* a = new int[t];
    int i = 0;

    while (x > 0) {
        a[i++] = x % 2;
        x /= 2;
    }

    return a;
}

void display(int r[], int t)
{
    int e = 0;
    if (r[t - 1] == 0)
        e = 1;
    for (int i = t - 1 - e; i >= 0; i--)
        cout << r[i];
}

int* sum(int a[], int b[], int t, int u)
{
    int z = t;
    if (u > t)
        z = u;

    for (int i = 0; i < z + 1; i++) {
        if (i >= t)
            a[i] = 0;

        if (i >= u)
            b[i] = 0;
    }

    int* c = new int[z + 1];
    int p[z + 1] = {};

    for (int i = 0; i < z + 1; i++) {
        c[i] = a[i] + b[i] + p[i];

        if (c[i] == 2) {
            c[i] = 0;
            p[i + 1] = 1;
        }

        if (c[i] == 3) {
            c[i] = 1;
            p[i + 1] = 1;
        }
    }

    return c;
}
int* product(int a[], int b[], int t, int u)
{
    int* q = new int[t + u];
    int k;
    int* sop = new int[t + u];
    sop = {};
    q = {};

    for (int i = 0; i < t; i++) {

        k = i;
        q = {};
        for (int j = 0; j < u; j++) {

            q[k++] = a[i] * b[j];
        }
        sop = sum(sop, q, t + u, t + u);
    }
    return sop;
}

字符串

8iwquhpp

8iwquhpp1#

只是为了让你给予一个C++的概念:

#include <iostream>
#include <vector>
#include <numeric>

using namespace std; // no don't use this.

int sum(const std::vector<int>& values)
{
    // numeric and algorith headers have a lot of things you can use
    return std::accumulate(values.begin(),values.end(),0);
}

int product(const std::vector<int>& values)
{
    int product = 1;

    // range based for loop, prefered over index based loops
    for(const int value : values)
    {
        product *= value;
    }

    return product;
}

int main()
{
    //std::vector<int> values(2);
    //std::cout << "Enter two decimal numbers:\n";
    //std::cin >> values[0] >> values[1];

    // for testing create a dynamically allocated
    // array with 4 values
    std::vector<int> values{1,2,3,4};

    std::cout << sum(values) << "\n";
    std::cout << product(values) << "\n";

    return 0;
}

字符串

相关问题