有人可以帮助我将此示例与C中的for循环相乘吗? 井,
我有char数组作为例子
x[]={ '0','3','0','8','9','6','4','3','8','4','0','0','7' };
* 765432,765432
我需要多个元素:
ZZZ=(0*7)+(3*6)+(0*5)+(8*4)+(9*3)+(6*2)+(4*7)+(3*6)+(8*5)+(4*4)+(0*3)+(0*2)=
0 +18 + 0 +32 +27 +12 +28 +18 +40 +16 +0 +0 = 191
您如何看待:
我试过了:
int mnozi = 0;
for (i = 0; i < 12; i++) {
//mnozi = (int)p[i]-48;
for (int j = 7; j > 1; j--)
mnozi = ((int)p[i] - 48) *j;
printf("\n%d", mnozi);
ZZZ = ZZZ + mnozi;
}
并且有一些奇怪的输出!
答案 0 :(得分:4)
有许多方法可以将数组乘以重复两次的降序7-2
模式。一个是通过模式的两次迭代简单地使用指针向下走x
。它可以用多种方式编码,另一种方式是:
#include <stdio.h>
int main (void) {
char x[]={ '0','3','0','8','9','6','4','3','8','4','0','0','7' }, *p = x;
int i = 7, r = 0, z = 0;
for (; *p && p < x + sizeof x; p++) {
printf (" %d * %d = %d\n", *p - '0', i, (*p - '0') * i);
z += (*p - '0') * i--;
if (i < 2) { i = 7; if (++r > 1) break; }
}
printf ("\n z : %d\n\n", z);
return 0;
}
示例使用/输出
$ ./bin/multcharray
0 * 7 = 0
3 * 6 = 18
0 * 5 = 0
8 * 4 = 32
9 * 3 = 27
6 * 2 = 12
4 * 7 = 28
3 * 6 = 18
8 * 5 = 40
4 * 4 = 16
0 * 3 = 0
0 * 2 = 0
z : 191
通过限制应用乘法的x
中的字符来限制迭代的轻微变化可能是:
char x[]={ '0','3','0','8','9','6','4','3','8','4','0','0','7' }, *p = x;
int i = 7, z = 0;
for (; *p && p < x + sizeof x - 1; p++) {
z += (*p - '0') * i;
printf (" %d * %d = %d\n", *p - '0', i, (*p - '0') * i);
if (--i < 2) i = 7;
}
printf ("\n z : %d\n\n", z);
变化无穷无尽。查看所有答案,如果您有任何问题,请告诉我们。
答案 1 :(得分:2)
使用嵌套循环似乎错了。试试这个:
#include <stdio.h>
int main(void) {
char x[]={ '0','3','0','8','9','6','4','3','8','4','0','0','7' };
char *p = x;
int i, ZZZ;
int mnozi = 0;
for (i = 0; i < 12; i++) {
//mnozi = (int)p[i]-48;
int j = 7 - i % 6;
mnozi = ((int)p[i] - '0') *j;
printf("\n%d", mnozi);
printf(" : i = %d, p[i] = '%c', i %% 6 = %d, j = %d", i, p[i], i % 6, j); /* to making what is happening clearer */
ZZZ = ZZZ + mnozi;
}
printf("\n%d\n", ZZZ);
return 0;
}
输出:
0 : i = 0, p[i] = '0', i % 6 = 0, j = 7
18 : i = 1, p[i] = '3', i % 6 = 1, j = 6
0 : i = 2, p[i] = '0', i % 6 = 2, j = 5
32 : i = 3, p[i] = '8', i % 6 = 3, j = 4
27 : i = 4, p[i] = '9', i % 6 = 4, j = 3
12 : i = 5, p[i] = '6', i % 6 = 5, j = 2
28 : i = 6, p[i] = '4', i % 6 = 0, j = 7
18 : i = 7, p[i] = '3', i % 6 = 1, j = 6
40 : i = 8, p[i] = '8', i % 6 = 2, j = 5
16 : i = 9, p[i] = '4', i % 6 = 3, j = 4
0 : i = 10, p[i] = '0', i % 6 = 4, j = 3
0 : i = 11, p[i] = '0', i % 6 = 5, j = 2
191