calculation in C program always results in 0 - c

This always results in 0 for me and I don't know why...
Other examples on internet generally cause of division.
in Codeblocks same code results normally but in Atom I have this problem.
please help.
#include <stdio.h>
#include <conio.h>
#define PI 3.14
int main() {
float r,a,c;
printf("enter radius: \n");
scanf("%.2f",&r);
c = r * PI * 2;
a = r * r * PI;
printf("area:%.2f circumference:%.2f \n",c,a );
return 0;
}

C11 7.21.6.2p3 says the following of fscanf et al:
3 [...] Each conversion specification is introduced
by the character %. After the %, the following appear in sequence:
An optional assignment-suppressing character *.
An optional decimal integer greater than zero that specifies the maximum field width (in characters).
An optional length modifier that specifies the size of the receiving object.
A conversion specifier character that specifies the type of conversion to be applied.
The length modifier means the extra letter(s) such as l in %lf meaning double. Notice that while %2f would be valid and would mean that only to 2 characters of input can be consumed, it is nowhere said that you can write %.2f, i.e. %.2f is an invalid conversion specification, and hence the behaviour is undefined (C11 7.2.6.2p13).

If there's no reason you want to use %.2f to scan, just using %f will work
#include <stdio.h>
#include <conio.h>
#define PI 3.14
int main() {
float r,a,c;
printf("enter radius: \n");
scanf("%f",&r);
c = r * PI * 2;
a = r * r * PI;
printf("area:%.2f circumference:%.2f \n",c,a );
return 0;
}
Example:
daniel#daniel-FX503VM:~/Documents/test$ ./zero
enter radius:
1
area:6.28 circumference:3.14
The .2 in the printf is a printing format specifier, and shouldn't have an impact on a scanf
Where you're putting the .2 in the scanf is actually the width field,which specifies the maximum number of characters to be read in the current reading operation (optionally). However, in this context, .2 characters as a width is not a meaningful sentiment, seeing as the width is required to be an integer.
If what you're actually trying to do is only read 2 characters, you could say
scanf("%2f", &r);
But be warned that the '.' would also count as a character.If you specifically just want the output to be two decimal places, then the proposed code above should suffice. If you want to round it internally, I'd suggest you read this post

Related

e format with printf not printing the desired output [duplicate]

I want to control the number of exponent digits after 'e' in C printf %e?
For example, C printf("%e") result 2.35e+03, but I want 2.35e+003, I need 3 digits of exponent, how do I use printf?
Code:
#include<stdio.h>
int main()
{
double x=34523423.52342353;
printf("%.3g\n%.3e",x,x);
return 0;
}
Result:
http://codepad.org/dSLzQIrn
3.45e+07
3.452e+07
I want
3.45e+007
3.452e+007
But interestingly, I got the right results in Windows with MinGW.
"...The exponent always contains at least two digits, and only as many more digits as necessary to represent the exponent. ..." C11dr ยง7.21.6.1 8
So 3.45e+07 is compliant (what OP does not want) and 3.45e+007 is not compliant (what OP wants).
As C does not provide a standard way for code to alter the number of exponent digits, code is left to fend for itself.
Various compilers support some control.
visual studio _set_output_format
For fun, following is DIY code
double x = 34523423.52342353;
// - 1 . xxx e - EEEE \0
#define ExpectedSize (1+1+1 +3 +1+1+ 4 + 1)
char buf[ExpectedSize + 10];
snprintf(buf, sizeof buf, "%.3e", x);
char *e = strchr(buf, 'e'); // lucky 'e' not in "Infinity" nor "NaN"
if (e) {
e++;
int expo = atoi(e);
snprintf(e, sizeof buf - (e - buf), "%05d", expo); // 5 more illustrative than 3
}
puts(buf);
3.452e00007
Also see c++ how to get "one digit exponent" with printf
printf Format tags prototype:
%[flags][width][.precision][length]specifier
The precision
... This gives ... the number of digits to appear after
the radix character for a, A, e, E, f, and F conversions ... .
You are using the conversion and the precision specifier correctly, the difference is with the implementations of the C library function and the environments on the differing systems. The precision specifies the number of digits after the '.' (dot, period, etc..). It does not set the number of characters that represent the exponentiation. The facts that it provides 3 digits on windows is just the way windows specifies the format, not the way the C standard library specifies that printf will work.
It would take comparing how the source implementations differ to see what is relied on for that piece of the format string. (it will probably boil down to some obscure difference in the way the windows v. linux/unix environments/locale/etc. are defined or specified)
char *nexp(double x, int p, int n) // Number with p digits of precision, n digits of exponent.
{
const int NN=12;
static char s[NN][256];//(fvca)
static int i=-1;
int j,e;
i=(++i)%NN; // Index of what s is to be used...
sprintf(s[i],"%.*lE", p,x); // Number...
for(j=0; s[i][j]; j++) if(s[i][j]=='E') break; // Find the 'E'...
if(s[i][j]=='E') // Found!
{
e= atoi(s[i]+j+1);
sprintf(s[i]+j+1, "%+0*d", n+1,e);
return s[i];
}
else return "***";
}
// Best Regards, GGa
// G_G

Formatting an doubel like xxxxE+xx in C

How can you format an double like 12345.0 to be printed as 1.234E+04?
I want to print something like this:
int N = 1024;
int time = 3476;
printf("%f", (N/time));
Where the output would be: 3.394531E+00
You could either use float for your variables or cast some of the variables to floating-point type like this:
printf("%f", ((float)N/time));
If you want to have your numbers always in Scientific notation http://www.cplusplus.com/reference/cstdio/printf/ you can replace the format with "%e".
It's worth noting that printf expects double by default for all f F e E g G a A.
As commented and answered by others #Some programmer dude: perform the division using floating-point math and not integer math.
Insure the correct a/b vs b/a is done to achieve "output would be: 3.394531E+00"
Use the "%.nE" format (where n is the precession) to print in exponential notation. "%E" alone will act like "%.6E".
"%e" is like "%E" except is uses an 'e' vs. 'E' in the output.
#include <stdio.h>
int main(void) {
int N = 1024;
int time = 3476;
printf("%.6E\n", 1.0*N/time);
printf("%.6E\n", 1.0*time/N);
printf("%.3E\n", 12345.0);
return 0;
}
Output
2.945915E-01
3.394531E+00
1.234E+04
First you need to avoid the integer division. Cast N to a double for instance (then the division will be with decimals).
And use the %e format (%E for a big-e), for 6 decimals:
printf("%.6E", (double)N/time);

expected expression before 'long'

I'm VERY new to programming, and I'm using a book to help me write some code that will solve ln(1+x) after the user inputs "x". My syntax is exactly the way the book has it in its example but I keep getting an error: expected expression before 'long' on line 28. Line 28 is the line that reads long double y = LOG(1+(x));.
#include <stdio.h>
#include <math.h>
#define LOG(X) _Generic((X),\
long double: log(1+(x))\
)
int main()
{
double x;
printf("Please enter a number from -1 to +1: ");
scanf("%f", &x);
long double y = LOG(1+(x));
printf("From C math library: ln(1+x) = %f\n", y);
}
Firstly, your generic macro is written for long double type. You supplied a double argument x. long double and double are two different types. You did not define a generic branch for double, which means that your macro will not compile for a double argument. Either change the type of x to long double or make your generic macro support double arguments.
Also, this is a very strange way to write a LOG macro. Why are you explicitly using 1 + (x) as log argument inside the macro? What if tomorrow you'll want to calculate LOG(2 + y)? Your macro will still insist on calculating log(1 + (x)) instead, which does not make any sense at all. A more sensible thing to do would be to just pass X to log
#define LOG(X) _Generic((X),\
long double: log(X)\
)
Secondly, in order to scanf a double value you need %lf format specifier. %f is for float. To printf a long double value you need %Lf format.
If you are new to programming, and trying to make an example work, I would not use macros at this stage but focus on the function and the data type. Start with a double which is the typical working type of the library interfaced by math.h. My example shows how to calculate the natural ln with the log() function.
As others have commented, scanf() needs a format specifier of %lf for a double, however printf() only needs the format specifier of %f for a double. Note that I have tested the return value from scanf() function as well as the number you input, to check that the input was well behaved.
Lastly, you invite numbers in the range -1 <= x <= 1 yet ln(0) is undefined, hence I have restricted the input range to exclude -1.
#include <stdio.h>
#include <math.h>
int main(void)
{
double x = 0, y;
printf("Please enter a number from -1 to +1: ");
if (1 != scanf("%lf", &x) || x <= -1 || x > 1) {
printf("I need -1 < number <= +1\n");
return 1;
}
y = log(x + 1);
printf("From C math library: ln(1+x) = %f\n", y);
return 0;
}
Here are some sample outputs:
Please enter a number from -1 to +1: -1
I need -1 < number <= +1
Please enter a number from -1 to +1: 0
From C math library: ln(1+x) = 0.000000
Please enter a number from -1 to +1: 1
From C math library: ln(1+x) = 0.693147

Floating point formatting till specified number

The following is a sample prog
#include<stdio.h>
#include<math.h>
main()
{
int x;
scanf("%d",&x);
printf("%.2f\n",(1/pow(2,x)));
}
Here I give .2f for floating point formatting. We can also give respective .3f or .5f etc according to requirement.
Suppose we do not know till what decimal after the '.' it is to be printed. I want to give something like a value n through input, so that it prints decimals till the n.
like .nf if n = 5 and x =1, it prints 0.50000 and for n = 3 it should print 0.500
How do I achieve this?
You can specify the desired precision as a variable:
int n = 5;
printf("%.*f\n", n, (1.0/pow(2,x))); /* equivalent to %.5f */
Quoting from man 3 printf:
An optional precision, in the form of a period ('.') followed by an
optional decimal digit string. Instead of a decimal digit string one
may write "*" or "*m$" (for some decimal integer m) to specify that the
precision is given in the next argument, or in the m-th argument,
respectively, which must be of type int.

Format Specifies in C for float datatype

int main()
{
system("color FC");
const float i=23.1234234;
printf("%5.4f",i);
getch();
return 0;
}
In above code , while printing float data type %5.4 format specifier is used.
I understood that .4 is used to get four numbers after decimal but whats the use of 5 before .4
The 5 is the length specifier. In this case, the printed float will take up at least 5 spaces. If it is shorter than that, leading spaces will be used.
(Though because of the precision 4, it will always be at least 6 characters long; the length modifier 5 in this case is a no-op.)
See documentation.
5 is used to right justify the output by 5 places i.e. the last digit will occur 5 places from cursor's initial position, if possible.
It is effective only when the length ( including the decimal ) is smaller than what is mentioned in the specifier.
e.g. printf("%5.4f",i);
till the specifier at the place of 5 is smaller than or equal than the length of the output
i.e 2(before decimal) + 4(after decimal, as chosen ) + 1 (the decimal itself) =7 , it has
no effect.
It will have effect here if it is at least 8.
At 7 it does what it should but you won's see any spaces.
5 is used to right justify the output by 5 places. Since the output is 10 character long so the effect is not seen. Now try this
#include <stdio.h>
int main()
{
const float i=23.1234234;
printf("%f\n",i);
printf("%5.4f\n",i);
printf("%7.4f\n",i);
printf("%10.4f\n",i);
printf("%12.5f",i);
return 0;
}
Output:
23.1234234
23.1234
23.1234
23.1234
23.1234

Resources