Incrementing 0.1 in C [duplicate] - c

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

Related

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.

5/9 is not taking by the C compiler to Calculate fc [duplicate]

This question already has answers here:
Division result is always zero [duplicate]
(4 answers)
Dividing 1/n always returns 0.0 [duplicate]
(3 answers)
Closed 5 years ago.
I'm stuck in a Code where I have to convert a temperature given by the user (in Fahrenheit) to degree Celsius. But unfortunately it's formula is not working with C Compiler.
#include<stdio.h>
#include<stdlib.h>
void c_f();
//void f_c();
float c,f,fc,fc1;
int main()
{
c_f();
// f_c();
return 0;
getch();
}
void c_f()
{
printf("\n Enter the temperature (in *F) to covert it into Celsius: ");
scanf("%d",&f);
fc=((5/9)*(f-32));
printf("\n %f*C",fc);
}
fc=((5/9)*(f-32));
Because 5 and 9 are integers, the arithmetic calculation is done at integer level, thus 5/9 == 0.
You should change it to floating point:
fc = ((5.0f / 9.0f) * (f - 32.0f));
Besides, format specifier %d is used for integers. If you want to read a floating point number, use %f:
scanf("%f", &f);
The result should be right now.
You have to use the correct format specifier which will be scanf("%f",&f) in this case.
Also fc=((5.0/9.0)*(f-32)), otherwise integer division yields 0.(Integer division truncates).5/9.0 will also work.
It is useless to put getch() after return statement. It will never reach upto that line.
What happens in your version?
Actually when two integers are divided the result is the quotient. If there any fractional part it is discarded. If you divide 5 by 9 the result will be 0.555.... When fractional part discarded it will be 0. So you always get 0.
Whenever you need an outcome of a division not t truncate you must make one of them floating point. That ensures that it(result) will not truncate.
So the program would be
#include<stdio.h>
#include<stdlib.h>
void celciusToFahreinheit();
float fahr_temp,celc_temp;
int main()
{
celciusToFahreinheit();
return EXIT_SUCCESS;
}
void celciusToFahreinheit()
{
printf("\n Enter the temperature (in *F) to covert it into Celsius: ");
if( scanf("%f",&fahr_temp) != 1 ){
fprintf(stderr,"Error in input\n");
exit(EXIT_FAILURE);
}
celc_temp=((5.0/9.0)*(fahr_temp-32));
printf("\n %f*C",celc_temp);
}
Apart from the problem few things would be - Using readable function name and checking the return value of scanf.

Program output is different from manual calculation why is this happening? C language [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 5 years ago.
#include <stdio.h>
#define s scanf
#define p printf
void main (){
int P,I,A;
float T,R;
clrscr();
p("PRINCIPAL: ");
s("%i",&P);
p("RATE: ");
s("%f",&R);
p("TERM: ");
s("%f",&T);
R = R/100;
I = P*R*T;
A = P+I;
p("I: %i\nMA: %i",I,A);
getch();
}
This really bugs me, if i put PRINCIPAL: 1200 RATE: 3 TERM:1 I: 35 MA: 1235 but if you compute in manually the answer should be I: 36 MA: 1236 the number is decreasing by 1. Why is it happening? why does the answer differ from computer and manual computing?
You try to typecast float to int that causes some data loss. Just like we can not store the big object in the small bag.
#include <stdio.h>
#define s scanf
#define p printf
int main (){
int P;
float T,R,I,A;
p("PRINCIPAL: ");
s("%i",&P);
p("RATE: ");
s("%f",&R);
p("TERM: ");
s("%f",&T);
R = R/100;
I = P*R*T;
A = P+I;
p("\nI: %f\nMA: %f",I,A);
return 0;
}
Your problem is with typecasting, please research on this subject a look at this, it's a little bit hude to explain in a simple text here.
But I can tell you, you are problably losing information when casting from float to int, because this two primitive types in C have diferent max length.
You can see changin the int variables to float and running your own program again, like this:
#include <stdio.h>
#define s scanf
#define p printf
void main (){
float P,I,A;
float T,R;
p("PRINCIPAL: ");
s("%f",&P);
p("RATE: ");
s("%f",&R);
p("TERM: ");
s("%f",&T);
R = R/100;
I = P*R*T;
A = P+I;
p("I: %f\nMA: %f",I,A);
getch();
}
This will produce your desired output, just in float.
Your problem is in the conversion of float to int. If you do your program with everything typed as float, you get the expected results:
#include <stdio.h>
#define s scanf
#define p printf
int main (){
float P,I,A;
float T,R;
p("PRINCIPAL: ");
s("%f",&P);
p("RATE: ");
s("%f",&R);
p("TERM: ");
s("%f",&T);
R = R/100;
I = P*R*T;
A = P+I;
p("I: %f\nMA: %f",I,A);
return 0;
}
outputs:
PRINCIPAL: 1200
RATE: 3
TERM: 1
I: 36.000000
MA: 1236.000000
However, when you convert your float values to int, you just take the integer part; everything to the right of the decimal point gets deleted. So, even though it's printing as 36.000000 when I do it, it's possible that the value of I may be coming out to something like 35.9999999, due to imprecision in floating-point math, and simply displaying as 36.000000 due to rounding in the display process. In this case, you'll just get the 35, and lose everything else.
To solve your problem, either leave everything as a float, or convert your floats to ints by rounding them—for example, by using lroundf in math.h—instead of just casting them.

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

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.

Resources