编程怎么写乘法竖式题

时间:2025-01-27 11:33:10 网络游戏

编写一个乘法竖式题的程序,可以使用不同的编程语言来实现。以下是几种不同编程语言的示例代码:

Python 示例代码

```python

def mul(a, b):

把两个整数分离开成为各位数字再逆序

aa = list(map(int, reversed(str(a))))

bb = list(map(int, reversed(str(b))))

n位整数和m位整数的乘积最多是n+m位整数

result = * (len(aa) + len(bb))

按小学整数乘法竖式计算两个整数的乘积

for ia, va in enumerate(aa):

c = 0

for ib, vb in enumerate(bb):

Python中内置函数divmod()可以同时计算整商和余数

c, result[ia + ib] = divmod(va * vb + c + result[ia + ib], 10)

result[ia + ib + 1] = c

整理,变成正常结果

result = int(''.join(map(str, reversed(result))))

return result

测试

for i in range(1000):

a = randint(1, 1000000000)

b = randint(1, 10000)

r = mul(a, b)

if r != a * b:

print(a, b, r, 'error')

```

C 示例代码

```c

include

include

include

int mul(int a, int b) {

// 把两个整数分离开成为各位数字再逆序

char aa, bb;

sprintf(aa, "%d", a);

sprintf(bb, "%d", b);

int len_aa = strlen(aa);

int len_bb = strlen(bb);

int max_len = len_aa + len_bb;

int result[max_len];

memset(result, 0, sizeof(result));

for (int ia = 0; ia < len_aa; ia++) {

int va = aa[len_aa - 1 - ia] - '0';

for (int ib = 0; ib < len_bb; ib++) {

int vb = bb[len_bb - 1 - ib] - '0';

int sum = va * vb + result[ia + ib];

result[ia + ib] = sum % 10;

result[ia + ib + 1] += sum / 10;

}

}

// 整理,变成正常结果

int final_result = 0;

for (int i = max_len - 1; i >= 0; i--) {

final_result = final_result * 10 + result[i];

}

return final_result;

}

int main() {

int a, b;

printf("请输入两个整数:");

scanf("%d %d", &a, &b);

int result = mul(a, b);

printf("%d * %d = %d\n", a, b, result);

return 0;

}

```

Java 示例代码