将double转换为int时出错

时间:2015-01-16 04:24:42

标签: c casting int double

我有一个代码,有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);
}

4 个答案:

答案 0 :(得分:2)

  

它仍然说错误:从指针转换为不同大小的整数

你不是在铸造&#34;加倍到int&#34; ...你正在铸造&#34; double *到int。&#34;

更改

int a = (int) (int1);
/*             ^^^^ this is a pointer */

int a = (int) (*int1);
/*             ^^^^^ this is a double */

答案 1 :(得分:0)

更改行

scanf("%lf", int1);
scanf("%lf", int2);

scanf("%lf", &int1);           //Use '&'
scanf("%lf", &int2);

不要使用指针变量。

答案 2 :(得分:0)

您的计划应该是什么样的:

#include <stdio.h>

int main( void )
{
    double value1;
    double value2;

    printf("Put in two numbers:");
    scanf("%lf", &value1);
    scanf("%lf", &value2);

    int a = value1;
    int b = value2;

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

传递给scanf的参数需要是适当变量的地址。所以你需要声明变量,例如double value1然后将该变量的地址传递给scanf,例如scanf(..., &value1);

C语言支持将double隐式转换为int,因此您根本不需要演员。隐式转换将截断数字。如果您希望将数字舍入为最接近的int,则需要使用round函数。

答案 3 :(得分:0)

正如我所看到的那样,您可以通过堆上的指针和动态内存以及一个具有自动值的方式执行此操作。

具有动态分配内存的指针

#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不会为指针分配内存。

相关问题