C Programming - Anomaly behaviour of while loop for float condition [duplicate] - c

This question already has answers here:
Float comparison gives different results
(7 answers)
Closed 6 years ago.
I wrote the following code:
#include <stdio.h>
int main ()
{
float x = 1.1;
printf("%s\n", "Hello!");
while (x == 1.1)
{
printf("%s\n", "Hey there!");
printf("%f\n", x);
x = x - 0.1;
}
printf("%s\n", "Bye!");
return 0;
}
However the output was (which I assume was not expected):
aps120797#XENON-PC:/mnt/d/Codes/LetUsC$ gcc C04Ag.c
aps120797#XENON-PC:/mnt/d/Codes/LetUsC$ ./a.out
Hello!
Bye!
To check if it accepts float condition or not, I wrote this code:
#include <stdio.h>
int main ()
{
float x = 1.1;
printf("%s\n", "Hello!");
while (x >= 1.0)
{
printf("%s\n", "Hey there!");
printf("%f\n", x);
x = x - 0.1;
}
printf("%s\n", "Bye!");
return 0;
}
And I got the output as I expected.
aps120797#XENON-PC:/mnt/d/Codes/LetUsC$ gcc C04Ag.c
aps120797#XENON-PC:/mnt/d/Codes/LetUsC$ ./a.out
Hello!
Hey there!
1.100000
Hey there!
1.000000
Bye!
So, my question is, what am I doing wrong in the first code?
UPDTATE: Just figured out how to correct this error.
Appended the while condition like this: while (x == 1.1f)

1.1 is not a float value, it's a double value.
When you write float x = 1.1; the compiler inserts an implicit cast: float x = (float)1.1;.
When you write x == 1.1 the compiler inserts another implicit cast: (double)x == 1.1.
So effectively you are testing whether 1.1 is still the same value after casting it to float and back to double - i.e. whether (double)(float)1.1 == 1.1 is true.
(double)(float)1.1 == 1.1 is not true, due to floating-point rounding error. At least on my platform:
1.1 is actually 1.100000000000000088817841970012523233890533447265625
(double)(float)1.1 is actually 1.10000002384185791015625
and as you can see these two numbers are not the same.

Related

Incrementing 0.1 in C [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Why are floating point numbers inaccurate?
(5 answers)
Closed last month.
#include <stdio.h>
int main()
{
float x,y;
scanf("%f %f",&x,&y);
for(float i = x;i<=y;i=i+0.1)
{
printf("%.1f ",i);
}
return 0;
}
This program is to Increment 0.1 in C programming. One of my Test case is (3.4) => x and (3.9) => y
I need print the numbers incremented by 0.1 till the value of y variable this test case is running successfully. But the another test case (9.4) => x and (10.2) => y this test case prints till 10.1 not 10.2 when we declare variables in float datatype. But in 2nd test case it prints till 10.2 when we declare variables in double datatype. And 1st test case gives logical error when we use double instead of float
#include <stdio.h>
int main()
{
double x,y;
scanf("%lf %lf",&x,&y);
for(double i = x;i<=y;i=i+0.1)
{
printf("%.1lf ",i);
}
return 0;
}
This runs successfully for the Test case 2

why doesn't My C code on Fermat's little theorem run properly after 10? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
I am a complete beginner and was just trying to apply what I have learned.
So I tried to make a C program that computes if a number passes the prime test in Fermat's little theorem.
Here is the code:
#include <stdio.h>
#include <math.h>
int main() {
double p, a, t;
printf("Enter the number tested to be prime: ");
scanf("%lf", &p);
a = 1;
t = 0;
while (a <= p && t == 0) {
t = pow(a, p) - a;
t = (int)t % (int)p;
a++;
}
if (t == 0) {
printf("prime test passed");
} else {
printf("prime test failed");
}
return 0;
}
So the problem is it works great until 10, but after that when I try it for 11 it just fails the test. Why is this happening?
for 11 it just fails the test. Why is this happening?
The reason for this concrete failure is likely not due to use of floating point math, but quite the contrary due to use of casting to an integer type by (int)t with a 4-byte int. In the course of your prime test, double t is assigned the value 811−8 = 8589934584, which can well be held in t, but not in an int with a maximum value of 231−1 = 2147483647.
Of course all this does not mean that you'll get much further if you just take this hurdle; soon you'd really encounter problems of floating point math. So the comment from Bob__ may indeed be a good advice.

Float, Double data types confusion in external functions (C) [duplicate]

This question already has answers here:
Reading in double values with scanf in c
(7 answers)
scanf is collecting the wrong input
(3 answers)
Closed 4 years ago.
The code below compiles alright:
#include <stdio.h>
double add(double summand1, double summand2)
{
double sum;
sum = summand1+summand2;
return sum;
}
double subtract(double minuend, double subtrahend)
{
double diff;
diff = minuend-subtrahend;
return diff;
}
int main()
{
double a,b,c,d;
printf("Enter Operand 1:\n");
scanf("%d",&a);
printf("Enter Operand 2:\n");
scanf("%d",&b);
// Add
c = add(a,b);
// Subtract
d = subtract(a,b);
printf("Sum: %.3f\n", c);
printf("Difference: %.3f\n", d);
return 0;
}
However, when entering 5 and 5 the result is 0.000 (wrong) and 0.000 (expected).
When entering a decimal number (e.g. 2.5), the second prompt is skipped altogether and two random numbers are printed for sum and difference.
The problem must be with the data types double and float, which I seem to be using incorrectly.
In your scanf()you used the format specifier %dwhich is used for integers. As you declared your whole variables as doubles use %lf (floating point) instead. I tried the code and with the correct specifier, the Code works.

c code doesnt work on turbo c++ with the float numbers

#include <stdio.h>
#include <math.h>
int main(void)
{
double r,d,x,y,pi;
clrscr();
printf("Input the value of r and degree: ");
//scanf("%f",&r);
//scanf("%f",&d);
r = 12;
d = 195;
pi = 3.14;
x = r * cos(d * pi/180);
y = r * sin(d * pi/180);
printf("The polar form is: (%f,%f)", x, y);
getch();
}
In the 1st case with defined values of r and d the output comes correct but in 2nd case when I give the input the output doesn't match with the original answer. The code worked on codeblocks but isn't working on turbo c++.
what am I doing wrong in turbo c++?
Mis-matched format specifier. Use "%lf" with a double *
double r,d,x,y,pi;
...
//scanf("%f",&r);
//scanf("%f",&d);
scanf("%lf",&r);
scanf("%lf",&d);
Better codes checks for success before using r.
if (scanf("%lf",&r) != 1) Handle_Error();
Output is Cartesian coordinates. #Jens. I'd also recommend a '\n'.
// printf("The polar form is: (%f,%f)", x, y);
printf("The Cartesian form is: (%f,%f)\n", x, y);
It appears Turbo-C requires "l" when printing double, so use
printf("The Cartesian form is: (%lf,%lf)\n", x, y);
Little reason to use a low precision pi. Suggest
pi = acos(-1.0);
In:
//scanf("%f",r);
//scanf("%f",d);
You need to pass the addresses of the variables, &r and &d.

Adding doubles in ansi C produces unexpected results

For my school project we are required to do math with doubles. My current code produces some unexpected results.
/* Hello World program */
#include<stdio.h>
int main()
{
double result = 0.0;
double x;
x = 10.0;
result = x + 10.0;
printf("%d", result);
return 0;
}
Upon running, this code prints: "-1267258024"
I don't understand why this happens? Why does the code not print 20.0?
Thanks!
EDIT: I'm so dumb. %d is for floats. Thank you!
The line
printf("%d", result);
indicates that you want to print an integer.
You probably want
printf("%f", result);
There are also things like %lf (acts the same as %f) and %Lf (works for long doubles) which you can read about on this answer.
A complete list of formatting options can be found here.

Resources