将double转换为int时出错

卢卡斯·蒂拉克(Lucas S Tilak)

我有一个输入为2双精度的代码,然后要将其转换为2个整数。我认为这可能是解引用问题,或者我的转换语法已关闭。提前致谢

#include <stdio.h>

int main()
{
    double * int1;
    double * int2;

    printf("Put in two numbers:");
    scanf("%lf", int1);
    scanf("%lf", int2);

    int a = (int) (int1);
    int b = (int) (int2);

    printf("%d\n%d", a, b);
}
泰勒·拉米雷斯(Taylor Ramirez)

如我所见,您可以通过两种方式执行此操作:一种是在堆上使用指针和动态内存,另一种是使用自动值。

具有动态分配内存的指针

#include <stdio.h>
#include <stdlib.h>
int main()
{
    double * int1 = malloc(sizeof(double));
    double * int2 = malloc(sizeof(double));

    printf("Put in two numbers:");
    scanf("%lf", int1);
    scanf("%lf", int2);

    int a = (int) *int1;
    int b = (int) *int2;

    printf("%d\n%d", a, b);
    free(int1);
    free(int2);
}

在系统堆栈上分配的自动值

#include <stdio.h>

int main()
{
    double int1;
    double int2;

    printf("Put in two numbers:");
    scanf("%lf", &int1);
    scanf("%lf", &int2);

    int a = (int) int1;
    int b = (int) int2;

    printf("%d\n%d", a, b);
}

注意:我在示例中使用指针的方式遇到的一个问题是它们所指向的内存不存在,我相信scanf不会为指针分配内存。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章