首页 > 解决方案 > 战俘();导致结果不一致的函数

问题描述

这是代码:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <math.h>

int findIntLen(int num); // A function that finds the amount of digits an integer has.

int main(void)
{
    int num = 0, temp = 0, res = 0;
    int index = 0, digit = 0;

    // Receive a number to be flipped from the user.
    do
    {
        printf("Please enter a positive integer to be flipped: ");
        scanf("%d", &num);
        getchar();
    } while (num < 1);

    temp = num;              // Assign the number value to a temporary variable so we do not lose our original value.
    index = findIntLen(num); // Generate an index variable that will be modified on each iteration.
    while (index > 0)
    {
        digit = temp % 10;                 // Find the next digit.
        res += digit * pow(10, index - 1); // Add the correct value to the result variable.
        temp = temp / 10;                  // Divide the temporary variable by 10 so we check the next digit on the next iteration.
        index--;                           // Subtract 1 from the index to multiply by correct power of 10 on next iteration.
    }
    /*  Example of the idea:
        if number is 15:
        digit count would be 2 therefor initial index would be 1.
        res += 5 * pow(10, 1) => 5 * 10 = 50

        * Next Iteration *
        Index is now 0:
        res += 1 * pow(10, 0) => 1 * 1 = 1

        FINAL RESULT: 51
    */

    printf("Flipped %d = %d\n", num, res); // Print final result.

    return 0;
}

int findIntLen(int num)
{
    int len = 0;

    while (num != 0)
    {
        num /= 10;
        len++;
    }

    return len;
}

当我使用 Visual Studio 运行它时,它工作正常,但是当我用 gcc 编译它时,最后一个数字似乎被减去 1。

使用 gcc 的非工作示例

视觉工作室中的一个工作示例

该程序旨在接收一个整数并翻转它,然后打印新的整数,如下所示:

程序的正确运行

如果有人知道这个问题的根源可能是什么,我很想知道。我正在使用Visual Studio 2019,gcc 版本gcc (MinGW.org GCC-6.3.0-1) 6.3.0,并且都在Windows 10pc 上运行。

标签: cvisual-studiogcc

解决方案


您的代码适用于我自己的 gcc ( gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04))。

但是,有些数字是整数,有些是长整数。在这两者相同的平台上,它没有任何区别。例如,在 int 为 16 位而 long 为 32 或 32 和 64 的平台上,您可能会得到未定义的行为。

然后,如果我可能会建议一种不同的方法,您可以将数字本身用作索引;你不需要使用pow()(这是对霍纳算法的改编)。

for (res = 0; temp; temp/=10) {
    res = res*10 + temp % 10;
}

我能想到的唯一解释是除以 10 会以某种方式累积错误。实际上不可能,因为错误应该首先出现在最右边的数字中,但是要么我必须相信魔法,要么我不相信。

尝试通过打印中间值来抓捕 gremlin(这是另一种方法,除法相同,但您可以轻松地检测原始代码):

printf("Let us start. Temp=%d\n", temp);
for (res = 0; temp; temp/=10) {
    printf("Iteration...\n");
    printf("  temp is now %d, last digit is %d\n", temp, temp % 10);
    res = res*10 + temp % 10;
    printf("  so, res is now %d\n", res);
}
printf("Finished.\n");

更新

最后我没有等待,给了我一个 MinGW-GCC。

第一件事:你的 GCC 是旧的。我有9.2.0,你好像安装了6.3.0。

第二件事,也是最后解释的错误:POW 是浮动的,它会出现错误(我应该首先注意到这一点)。为了节省时间,我只是在循环中放了一个简单的诊断打印输出。它应该列出十乘七的幂——但它没有。

在此处输入图像描述


推荐阅读