Lucas S Tilak
Lucas S Tilak

Reputation: 47

Error in converting double to int

I have a code that has 2 doubles as an input and then I want to convert it to 2 ints. I think it's either a problem with dereferencing or my casting syntax is off. Thanks in advance

#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);
}

Upvotes: 2

Views: 1920

Answers (4)

zeitue
zeitue

Reputation: 1683

As I see it you could do this two ways one using pointers and dynamic memory on the heap and one with automatic values.

Pointers with dynamically allocated memory

#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);
}

Automatic values allocated on the system stack

#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);
}

Notes: one issue I see with the way pointers are used in your example is that there is no memory in which they are pointing to and I do believe scanf does not allocate memory for a pointer.

Upvotes: 0

user3386109
user3386109

Reputation: 34839

What your program should look like:

#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);
}

The parameter passed to scanf needs to be the address of an appropriate variable. So you need to declare the variable, e.g. double value1 and then pass the address of that variable to scanf, e.g. scanf(..., &value1);.

The C language supports implicit casting of double to int, so you don't need a cast at all. The implicit conversion will truncate the number. If you want the number rounded to the nearest int, then you will need to use the round function.

Upvotes: 0

Drew Dormann
Drew Dormann

Reputation: 63946

It still says error: cast from pointer to integer of different size

You aren't casting "double to int"... you're casting "double* to int."

Change

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

to

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

Upvotes: 2

Himanshu
Himanshu

Reputation: 4395

Change your Lines

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

To

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

dont use pointer variable for this.

Upvotes: 0

Related Questions