Reputation: 23
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!
Upvotes: 2
Views: 48
Reputation: 1644
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.
Upvotes: 1
Reputation: 148
Just a few corrections in your code:
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.
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;
}
Upvotes: 0