【发布时间】:2019-04-02 21:10:06
【问题描述】:
我的编程任务是使用数组对长度不超过 20 位的大整数执行加法和减法运算。这些指令告诉我们在从数组末尾开始存储数字时执行算术运算。例如:
string value1 = "";
cin >> value1; //input 1234
test[19] = 4;
test[18] = 3;
test[17] = 2;
test[16] = 1;
因此执行和和差运算会更容易。任何未使用的数字都应初始化为 0。
我首先编写了一个 for 循环来读取 test[] 数组的最后一个索引到第一个索引。变量 numDigits 跟踪数组中的所有非零值。
include<iostream>
include<string>
using namespace std;
int main()
{
string value1 = "";
int numDigits = 0;
const int Max_Digits = 20;
int test[Max_Digits] = {0};
test[19] = 10;
//cin >> value1;
for (int i = Max_Digits - 1; i >= 0; i--)
{
if (test[i] != 0)
numDigits++;
}
cout << "There are " << numDigits << " nonzero values."; //numDigits == 1
/*cout << "Your number is: " << test[];*/
return 0;
}
因此,如果用户在字符串变量 value1 中输入“1234”,我希望程序在继续赋值之前将字符串转换为数字数组并输出 1234(无逗号或空格)。
【问题讨论】:
-
你知道如何遍历一个字符串吗?你知道如何将字符“4”转换为数字
4吗?你知道如何将元素放入数组吗? -
如果用户发疯了,输入了超过 20 个数字会怎样?你不应该改用向量吗?
-
@ConstantinosGlynos 验证稍后进行。现在,我想先将字符串转换为 int 数字数组。另外,我的教授还没有给我们讲过向量,而且说明书上也没有提到它们是一个选项。
-
@UchennaOnuigbo:很公平......您需要将数字向后插入数组还是向前插入?那么,如果用户插入“1234”,你希望数组中的第一个元素是1,还是4?
-
@ConstantinosGlynos 如果用户插入“1234”,那么第 19 个索引将为 4,然后为 [18] 为 3,为 [17] 为 2,最后为 [16] 为 1。其余元素初始化为 0
标签: c++ arrays loops console-application