This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 7 years ago.
When I wrote a simple program to read and print a number using float, I came across some unexpected results.
In the following program when I entered a number 100.62, the result I got was 100.620003. Only upto eight digits the value showed correctly. Even when I tried different numbers the issue persisted. Why is this? Is there a way to overcome this problem other than by limiting the decimal points.
And also is there a way to print a digit as it is? ie; if I enter 100.62 it should print 100.62 and if enter 100.623 it should print 100.623 (not 100.620000 and 100.623000).
int main (void)
{
float i;
printf ("Enter a number : ");
scanf ("%f", &i);
printf ("You entered the number : %f", i)
return 0;
}
This issue comes from how computers handle the float values.
One way to overcome this problem is stopping using float and deal the numbers as decimal data.
To print a digit as it is, just read input as a string and print it. This method is very simple and can support difficult inputs such as 1e-10000 or 1.00000.
As far as I know, the C always display those complete digits of float in default.
If you want to display custom decimal points, you should try using ".x" before the f notation. X is the total number that you want to show after the dot. For example:
float i;
printf ("Enter a number : ");
scanf ("%f", &i);
printf ("You entered the number : %.2f", i)
return 0;
this will result 2 numbers after the dot. If you input 100.62, it will show as 100.62. However, this is static. I mean, if you input 100.623, it will show 100.62, not 100.623. You should know exactly how many numbers after dot that you want to show.
Related
This question already has answers here:
What happens when I use the wrong format specifier?
(2 answers)
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 1 year ago.
This is the code-
int j;
printf("Enter the number:");
scanf("%c",&j);
printf("You have enter the decimal number %i \n",j);
printf("You have enter the octal number %o\n",j);
printf("You have enter the hexadecimal number %x\n",j);
printf("You have enter the character %c\n",j);
This is my output:
Enter the number:r
You have enter the decimal number 4201074
You have enter the octal number 20015162
You have enter the hexadecimal number 401a72
You have enter the character r
The %c format specifier to scanf expects a char * as a parameter. You're instead passing in an int *.
Using the wrong format specifier triggers undefined behavior which is why you're seeing strange results. What's probably happening behind the scenes is that only the first of the (presumably) 4 bytes of the int variable j are written to, leaving the rest uninitialized and containing whatever garbage was there previously.
Change the type of j to char and you should get the results you expect.
This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Division result is always zero [duplicate]
(4 answers)
How to print using scanf() function in C programming? [closed]
(2 answers)
Closed 2 years ago.
I'm new to c and im trying to learn how to use the scanf function to pass in data and then the printf function to show me the printed results.
This seems like it should be eas,y but my expected outputs do not match what gets returned. My IDE is vscode
#include <stdio.h>
#define pi 3.14159
int main()
{
float size;
float radius;
scanf("this is the value : %f",&radius);
size = (2/3)*pi*(radius*radius*radius);
printf("%f",size);
return 0;
}
here you can see what i inpute and what gets printed
After that I went to make an easier program to understand the concept and I'm getting a similar but different issue. instead of returning 0 every time now it prints the same constant
#include <stdio.h>
int main()
{
int a;
scanf("This is the value %d", &a);
printf("Input value read : a = %d", a);
return 0;
}
Here you can see the output i get for the second program
Any ideas for whats going wrong and how i could fix it?
You seem to expect scanf to print a message and then to acquire a value:
scanf("this is the value : %f",&radius);
No. This obtained just by printing the message and then aquiring the value with scanf:
printf("Please insert the value :\n");
if (scanf ("%f",&radius) == 1)
{
/* ... */
}
Please note the check on scanf return value, that is the number of variables succesfully aquired. In this case we expect it to be 1, as the only format specifier is %f.
That message before %f made scanf actually expect exactly that string (whitespaces included) before the float number. Inserting just the input number (5, in your example) made scanf discard the input as it wasn't matching the given string, and no value was stored, so that radius remained uninitialized and the execution resulted in undefined behavior. Additionally, that leading 2/3 is calculated with integer arithmetics and the result is 0; use 2.0/3.0 to force the use of float arithmetics.
The issue with the test involving %d is quite similar; you just see the random uninitialized value of a that is not written by scanf for the reasons explained above.
I have a program which takes input from the user and tells the user which number is bigger num1 or num2. My problem is that i don't want to allow the user to enter a decimal number such as 1.2 etc.
Here is my program so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int num1;
int num2;
printf("enter a number: ");
scanf("%d", &num1);
printf("enter another number: ");
scanf("%d", &num2);
printf("\n");
printf("\n");
if (num1 < 0) {
printf("Enter a value which is not below 0!");
}
else if (num1 == num2) {
printf("%d and %d are equal", num1, num2);
}
else if (num1 > num2) {
printf("%d is bigger than %d", num1, num2);
}
else if (num2 > num1) {
printf("%d is bigger than %d", num2, num1);
}
return 0;
}
Currently my program displays an error message if a user enters a negative number.
But I want to deter and stop any decimal numbers from being entered at all weather below 0 as a negative number or not.
You cannot, with standard Console input, prevent the user from entering arbitrary strings. (That would require to receive every single character as it is typed, and suppress "illegal" characters, which is both system specific). So you are stuck with receiving a stream of input and checking its contents. If the input was wrong, you can prompt the user to try again.
There are two basic ways:
You do read floating point numbers with %f. This format skips any whitespace, then tries to parse a number from the following word, and stops when it encounters a character which does not let it continue parsing a number. (That is typically another whitespace separating it from the next number but could be a letter or any other non-numerical character.) Then you check whether it is a whole number. The easiest way to do that is to cut the fraction part of the parsed value and see whether it is equal to the parsed float. An easy way to cut off any decimal places is to truncate it to int: if((int)f != f) { /* user entered a number with decimal places */ }.
You read a word from the input as a string (%s) and parse it manually. That's more complicated but actually a pretty neat beginner exercise, in particular if you try to come up with all possible stupid inputs (unprintable characters, very long words, several minus sings etc.) and test and harden your routine against them.
One important advice: Whatever way you decide to go, make sure to evaluate the return value of the input routine. I see that you do not evaluate the return value of scanf in your program, but that is essential. scanf returns the number of successfully converted items (i.e. in your case 1 if a number could be read). If scanf returns 0, it could not parse a number from the input (for example because the first character in the input is a decimal point which cannot be part of an integer number), and you have to perform some kind of error handling. In particular, you must read away the offending word (or line? Depends on the strictness you want to impose on the input format) of the input.
Another advice on the side is to prepare your program for non-interactive use. This means that there is nobody sitting in front of a console entering numbers and hitting enter — instead the standard input comes from a file or another program. In order to provide input from a file one would write myprog < sometextfile.txt in a Console on Windows as well as in a Linux etc. terminal. Programs profit enormously from being "scriptable"; it also makes it easy to quickly test them against many kinds of input in a repeatable fashion. But if the input comes potentially from a file there is, for example, no need to expect every number (or every pair of numbers) to be on its own line.
1.2 is not a decimal data type. It is a float data type!
As you've used %d in the scanf, the value before . will get stored in num1 and 0 will be stored in num2;
int num1,num2;
scanf("%d%d",&num1,&num2);
printf("%d %d",num1,num2);
if entered 1.2 & 3.4
o/p:- 1 0
if entered 1 & 3.4
o/p:- 1 & 3
Try this concept - 'Scanset' or 'Negated Scanset'
scanf("%[^.]", &num1); // does not allow decimal point (.) and will accept not only number but all other characters
or
scanf("%[0-9]", &num1); // only accept positive integer
This question already has answers here:
"printf" only printing variable addresses
(2 answers)
Closed 3 years ago.
So I'm using C for a few days and I didn't have this problem before but now I have a problem with C scanning different number than the one the user enter. I feel like it prints the location of the number but not the number itself. The number I get every time is 6422076 and if I print another number that I've scan from the user it just show the same number -4, 6422072 so I'm pretty sure It has to do with the location the computer storage the numbers.
I tried to print it with a few other ways and always get the same weird number.
void measures()
{
int height;
printf("\nEnter your height:\n");
scanf("%d",&height);
while(height<140 || height>210){
printf("Invalid input, try again: \n");
scanf("%d",&height);
}
printf("height: %d\n",&height);
}
not getting any errors
Here's your problem:
printf("height: %d\n",&height);
You're not printing the value of height. You're printing its address. Remove the address-of operator:
printf("height: %d\n",height);
#include <stdio.h>
int main (void) {
int count, value;
double avg, sum;
count = 0;
sum = 0;
printf("please input how many integers you have \n");
scanf("%d", &count);
for (int i = 0; i < count; i++) {
printf("please input your values \n");
scanf("%d", &value);
sum = sum + value;
}
avg = sum / count;
printf("your average is " "%f", avg);
}
Example: count input is 4. input values is 7.6, 1, 2, 3.
I understand that in the for loop scanf sees 7.6 first, but disregards the decimal point as it is not a valid form of input, and passes it along every subsequent scanf in the loop though they never truly accept an input. This results in the only inputted value as 7, but then the program should continue to divide 7 by 4 to retrieve the "Expected" average, but that is not the case. I end up with 7.000000, which I can't figure out why is happening.
Disregard the fact that I am prompting the user to input integer values even though floating point values were inputted because it is part of my homework assignment. Any hints or references to what I should study would be great
I understand that in the for loop scanf sees 7.6 first, but disregards the decimal point [..]
No. That's a matching failure as the input you enter (7.6) doesn't match the format specifier %d. Hence, scanf() fails. That's why you should always check the return code of all the standard functions. See 7.21.6.2 The fscanf function.
If you want to be able to read floating point values then you should read (change your code) to read floats (or doubles).
For example to read a double:
double value;
if (scanf("%lfd", &value) != 1) {
/* handle failure */
}
A general suggestion: Don't use scanf() if at all possible. Please read Why does everyone say not to use scanf? What should I use instead? for further explanation.
Your reasoning seems to be correct, except for the assumption that scanf will set value to zero on the subsequent iterations. Instead, after reading up to the period on the first iteration and assigning 7 to value, on subsequent iterations scanf will see the period, conclude that the input doesn't match the format, and not touch value at all, leaving it as 7 on every iteration. (It should return 1 on the first iteration and 0 on subsequent ones, to indicate the number of items matched and assigned)
So, the loop will add 7 on every iteration, and then divide by the number of iterations, giving a result of 7.