【问题标题】:getting unexpected output for entered number to find the cube获得输入数字的意外输出以查找多维数据集
【发布时间】:2019-03-20 15:43:06
【问题描述】:

这里我不只是想找出任何数字的立方体,但我想找出输入的数字是乘以它的位数。 例如:- 100 乘以 100 三倍。

每当我输入多于 3 位的数字时,我都会得到 负数的意外输出。

#include<stdio.h>
#include<conio.h>

int cube(int);

void main()
{
    int n,ans;

    printf("enter a number : ");
    scanf("%d" , &n);

   ans=cube(n);
    printf("%d" , ans);
}

int cube(int num)
{
    int count,temp,i,add=1;

    temp=num;
    while(temp>0)
    {
        temp=temp/10;
        count++;
    }
    printf("%d\n" , count);

    for(i=1;i<=count;i++)
    {
        add=add*num;
    }

    return add;
}

例如:-

输入一个数字:1000
4
-727379968

但在我输入数字为 10101 的同时

输入一个数字:10101
5
1343051877

我得到了这个输出。

【问题讨论】:

  • 专业提示:当你得到这样的无意义值时,几乎总是未初始化变量的情况。 count 在递增之前设置为什么?答:没什么特别的。由于编译器认为你不在乎,它只是使用 whatever 作为值。使用-Wall 编译以暴露此类问题。

标签: c


【解决方案1】:

您遇到了溢出,因为 1000^4 是 1000000000000,这肯定高于 INT_MAX 的值(在我的系统上为 2147483647)。您应该使用适当的数据类型,如 long 或检查这样的溢出:

#include<limits.h>


int cube(int num)
{
    int count,temp,i,add=1;

    temp=num;
    while(temp>0)
    {
        temp=temp/10;
        count++;
    }
    printf("%d\n" , count);

    for(i=1;i<=count;i++)
    {
        if (INT_MAX/num < add) {
            printf("overflow\n");
        }
        add=add*num;
    }

    return add;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 2022-12-10
    • 2012-11-08
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 2021-11-19
    • 2021-10-24
    相关资源
    最近更新 更多