数组的加法和减法
Addition and subtraction of arrays
本文关键字:数组 更新时间:2023-10-16
我已经为此工作了一整天,但就是无法获得正确的输出。我想做的是输入两个数字,这些数字将被推入两个数组,这样我们就可以对它们进行减法或加法运算,并显示结果。看起来很简单,但很少捕捉到
- 输入必须从用户一个接一个地推送到数组中
- 如果我没有输入值,代码应该假设它是
'0'
或'null'
。CCD_ 3如果在开始,而CCD_。例如,如果第一个数字是234
,第二个数字是23
,那么代码应该将其转换为'023'
,如果我将第一个数字输入为2
,将第二个号码输入为3
,但最后没有输入任何内容,那么代码应假定其为null
问题
- 如果总和大于
10
,我不能把"进位"带入下一个集合。这意味着我得到的值只是两个数字的相加,不管它是否大于10。例如234
和890
的相加就是[10, 12, 4]
这是代码。。。。。
#include<iostream>
using namespace std;
main() {
int first[10], second[10], result[10], c, n;
cout << "Enter the number of elements in the array ";
cin >> n;
if (n > 10 || n < 0) {
std::cout << "invalid number, you are a bad reader" << endl;
system("PAUSE");
return 0;
}
cout << "Enter elements of first array " << endl;
for (c = 0; c < n; c++) {
cin >> first[c];
if (first[c] > 9 || first[c] < 0) {
std::cout << "invalid number, you are a bad reader" << endl;
system("PAUSE");
return 0;
}
}
cout << "Enter elements of second array " << endl;
for (c = 0; c < n; c++)
cin >> second[c];
cout << "Sum of elements of two arrays " << endl;
for (c = 0; c < n; c++)
cout << first[c] + second[c] << endl;
if ((first[c] + second[c]) > 9) {
cout << "overflow" << endl;
}
//result[c] = first[c] + second [c];
//cout << result[c] <<endl;
system("PAUSE");
return 0;
}
如果能给我一些建议,我将不胜感激。
如果您的意图是获得例如的结果
234 + 890 = 1124
那么求和循环的顺序应该相反。(由于您正在从提示中读取数组的元素数量,您可以使用此信息按照以下求和循环的首选顺序将第一个/第二个数字输入到每个数组中。)
例如,对于进位问题,您需要设置一个变量并在循环中使用它。
int sum[10] = {0};
int c;
int carry = 0;
for (c = 0; c < n; c++)
{
sum[c] = first[c] + second[c] + carry;
carry = sum[c] / 10;
}
if (c < n)
sum[c] = carry;
else
cout << "overflow";
使用std::vector并学习如何使用反向迭代器。因此,如果有人输入234,则push_back(2)、push_back(3)、push_back(4),并且[0]=2、[1]=3、[2]=4。如果下一个数字是23,则[0]=2,[1]=3。现在,使用反向迭代器遍历两个向量,因此对rbegin()的第一个调用将给出一个指向[2]=4的指针,而另一个向量将给出[1]=3。现在使用push_back将结果相加并进位到第三个向量中以存储结果。使用反向迭代器输出结果以打印结果。
这看起来像是家庭作业,所以没有示例代码。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '