2

I am new in C language and I am trying to make a program that is able to take a decimal number and print out the closest number to that decimal, However, when I try to run the program it only asks me for the decimal number and nothing else.

# include<stdio.h>
int main()
{
    float num;
    printf("Enter a double number: ");
    scanf("%d", num);
    int r=0;
    if(num<0)
    {
        r=r+num-0.5;
    }
    else
    {
        r=r+num+0.5;
    }
    printf("The closest integer to %d: %d", num, r);

    return 0;
}

If you could help me find the issue with my program I would be very thankful. Thank you!

mrblackmuf
  • 23
  • 3
  • 1
    Please take note of compiler warnings: `scanf("%d", num);` should be `scanf("%f", &num);` Then in `printf()` you are again using `%d` but passing a `float` for it. – Weather Vane Oct 19 '20 at 13:47

2 Answers2

1

You have multiple issues in your program. First of all take a look at this chart, you are using variable types wrong. You are intend to receive a floating point number from the stdin, but you are scanning a %d, which is a normal integer. Use %f instead. This is also an issue while printing the output.

scanf("%f", &num); // more about the & later

Second thing, you might not get used to pointers, and memory handling yet, but if you have a trivial data structure - like an int, float, etc.. - you must scan your data, and write it in the memory allocated for your variable, so you have to pass the memory address of num by doing &num.

scanf("%f", &num); // you are passing the memory address of your variable

You can try it out by:

printf("%p\n", (void*)&num);

(How to printf a memory location)


Full working example:

# include <stdio.h>

int main() {
    float num;
    
    printf("Enter a double number: ");
    scanf("%f", &num);

    int r=0;
    if(num<0) {
        r=r+num-0.5;
    }else {
        r=r+num+0.5;
    }

    printf("The closest integer to %f: %d", num, r);

    return 0;
}

These errors should not terminate the program, just produce false results. Let me know if you have further issues.

nagyl
  • 1,644
  • 1
  • 7
  • 18
0

Just a few corrections in your code:

  1. You are asking for a decimal number which is of type float. Therefore in scanf to read a float data type you have to use %f instead of %d which is for integer data type. The same in the last printf statement.

  2. In the scanf statement instead of num you should use &num. You have to point to the memory location of the variable you are attempting to get input for.

Here is the correct code.

# include<stdio.h>
int main()
{
    float num;
    int r = 0;
    printf("Enter a double number: ");
    scanf("%f", &num);

    if(num < 0)
    {
        r = r+num-0.5;
    }
    else
    {
        r = r+num+0.5;
    }
    printf("The closest integer to %f is %d\n", num, r);

    return 0;
}
Emotional Damage
  • 138
  • 1
  • 1
  • 9