提问人:محمد محمدنژاد 提问时间:11/16/2023 最后编辑:Alan Birtlesمحمد محمدنژاد 更新时间:11/16/2023 访问量:61
C++ 代码未在编译器中运行产品函数
c++ code didn't run product function in compiler
问:
我该怎么办 产品函数没有在编译器中运行某些数字,例如 a=511 和 b=512 也 sum 函数没有运行,请帮我调试它,我需要你的帮助,期待它给我 我是学生,我正在学习 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;
}
答:
1赞
Pepijn Kramer
11/16/2023
#1
只是为了让您了解 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;
}
评论
0赞
wohlstad
11/16/2023
product
可以更一致地与:。sum
return std::accumulate(values.begin(), values.end(), 1, std::multiplies<int>{});
2赞
Pepijn Kramer
11/16/2023
@wohlstad你是对的,或者甚至使用 std::reduce...我的观点是还要显示一个 for 循环;)我的主要观点是试图反驳所有仍在教授的“C”风格编程
评论
int* q= new int[t + u];
int* q = new int[t * u];
new
std::vector<int>
您应该使用它而不是使用类似 .然后,您的函数不应该返回,而是返回 std::vector<int>。如果你继续这样编码,你最终只会有大量的内存泄漏。int* sop = new int[t + u];
int*