我无法弄清楚这个循环和C中的数组加法[关闭]

问题描述 投票:-4回答:1

[我正在编写一个程序,该程序使用循环在每次迭代时为称为(prod)的变量生成以下值:

3
12
5
14

我的问题是:(1)我如何存储值,使其看起来像int pro = 312514; (没有空间,并且每次迭代后都没有替换当前值]

First iteration
int pro = 3

Second iteration
int pro = 312

Third iteration
int pro = 3125

Fourth iteration
int pro = 312514

((2)最后,我想在变量中添加每个数字。 pro(即sum = 3 + 1 + 2 + 5 + 1 + 4 = 16)[如果数据类型为int,我可以算出如何实现这一部分]

编辑

Using an  array will look like
Int  pro [array_size] = {3, 12, 5, 14}.
--------------
Sum will then be
3 + 12 + 5 + 14 = 34

BUT WHAT I WANT TO ACHIEVE IS
3 +1+2+5+1+4 = 16
-----------------

希望我的问题很清楚并且是TIA

c arrays typeconverter
1个回答
0
投票

((1)如何存储该值,使其看起来像int pro = 312514;

基本上,您有2个选项:存储为整数或存储为字符串

如果选择整数,则需要将当前pro乘以10(或100)并从循环中添加该值;

int pos = 0;
pos *= 10;  pos += 3;  // first loop
pos *= 100; pos += 12; // second loop
pos *= 10;  pos += 5;  // third loop
pos *= 100; pos += 14; // fourth loop

如果选择字符串,只需连接先前的pro和循环中的值。

#include <string.h>
char pos[100] = {0}, pos2[100];
sprintf(pos2, "%s%s", pos, "3");  strcpy(pos, pos2); // first loop
sprintf(pos2, "%s%s", pos, "12"); strcpy(pos, pos2); // second loop
sprintf(pos2, "%s%s", pos, "5");  strcpy(pos, pos2); // third loop
sprintf(pos2, "%s%s", pos, "14"); strcpy(pos, pos2); // fourth loop

(2)最后,我想在var中添加每个数字。亲...我可以弄清楚如果数据类型为int,如何实现这一部分]

隔离最低有效位(pro % 10)并将其添加到当前总数中。然后将pro除以​​10,并重复直到达到0

currenttotal = 0; pro = 312514;
currenttotal += (pro % 10); pro /= 10; // currenttotal = 4;  pro = 31251
currenttotal += (pro % 10); pro /= 10; // currenttotal = 5;  pro = 3125
currenttotal += (pro % 10); pro /= 10; // currenttotal = 10; pro = 312
currenttotal += (pro % 10); pro /= 10; // currenttotal = 12; pro = 31
currenttotal += (pro % 10); pro /= 10; // currenttotal = 13; pro = 3
currenttotal += (pro % 10); pro /= 10; // currenttotal = 16; pro = 0
© www.soinside.com 2019 - 2024. All rights reserved.