我的系统显示正确代码的错误输出,而同一代码在其他 device.How 中给出正确输出以纠正此问题?

My system is showing wrong output for correct code and the same code is giving correct output in other device.How to rectify this issue?

我用c语言写了代码(n阶乘)。

代码为-->

#include <stdio.h>
#include <string.h>

int main()
{
    int n;
    scanf("%d", &n);
    char str[200];
    str[0] = '1';
    int k;
    int t = 0;
    int carry = 0;
    for (int i = 1; i <= n; i++)
    {
        carry = 0;
        for (int j = 0;; j++)
        {
            int arr = str[j] - 48;
            k = arr * i + carry;
            arr = k % 10;
            str[j] = arr + 48;
            carry = k / 10;

            if (carry == 0 && str[j + 1] == '[=11=]')
            {
                break;
            }
            if (carry != 0 && str[j + 1] == '[=11=]')
            {

                for (int r = j;; r++)
                {
                    str[r + 1] = (carry % 10) + 48;
                    carry = carry / 10;

                    if (carry == 0)
                    {
                        str[r + 2] = '[=11=]';
                        t = 1;
                        break;
                    }
                }
                break;
            }
        }
    }
    int len = strlen(str);
    // // printf("%d\n",len);
    char prr[200];
    for (int i = 0; i < len; i++)
    {
        int b = len - i - 1;
        printf("%c", str[b]);
        
    }
    // printf(" %s\n", str);

    return 0;
}

在其他系统(包括在线c编译器)中显示正确答案

输入=7
输出=5040

在我的系统(笔记本电脑)中:

输入=7 输出=+,*)'040

我的笔记本电脑是 hp envy 13-ab070TU

os:Windows 10 家

系统 type:64 位操作系统,基于 x64 的处理器

我也在 ubuntu 和 kali 上的笔记本电脑的虚拟机上尝试了我的代码,但结果是一样的,它显示了错误的输出。

这是什么原因,我该如何解决这个问题?

您正在向 str 数组中填充数字,但是 str 不是 必须是正确的、以 null 结尾的字符串。

最后,您调用 strlen(str) 来了解您在结果中计算了多少位数。但由于 str 不一定是空终止字符串,因此 strlen 不一定得到正确答案。

str 是一个本地(堆栈分配)变量,并且您没有给它一个初始值设定项,所以它开始时包含不可预测的垃圾。

如果 str 刚好开始包含零(可能),您的程序就会正常运行。但是,如果它包含一个或多个非零字节,strlen 可能会计算出太长的长度,因此您最后的数字打印循环可能会打印一些额外的字符,就像您在笔记本电脑上看到的那样。

有两种或三种方法可以解决这个问题。

  1. 调用memset(str, '[=18=]', sizeof(str));用0填充数组。
  2. 初始化数组:char str[200] = "";。 (事实证明,将用 0 填充整个数组。)
  3. 以其他方式记录位数。我怀疑这是 kr 或类似的东西所取得的最大值。