I am new with c and I'm trying to use doubles variable. Unfortunately, the compiler (Code::Blocks) seems to ignore absolutely what i'm writing.
#include<stdio.h>
int main()
{
double x=1.03;
printf("x: %lf",x);
return 0;
}
and the output is:
x: 0.000000
what is the problem?
Use %f instead of %lf. Doubles only need %f; see the "specifiers" table here.
If printf is looking for a larger value than you are providing, what prints out will be affected by what happens to be in memory near the x argument that you provided. In this case, I'm guessing that's 0.
Edit: Thanks to #Olaf for pointing out that the specification says %lf should work just fine. Apparently the OP's compiler or compiler version is nonstandard. Alternatively, perhaps the project settings are selecting nonstandard compiler behaviour. (I suppose the compiler or library implementation of printf could be buggy, as well.)
Related
I write c embedded on STM32F437VI. At some point, I need to parse some strings that contain numbers, as float numbers. I use atof and it works always with the correct result, except for this one weird case. If the string is 0 or 0.0 it gives 2.
I have included stdlib.h and even tried (float)atof() to typecast, but for some weird reason, the float variable has always the value 2 from the atof("0") operation and the double value has the correct 0.
Why is this happening? Thank you all in advance.
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
char test[] = "0";
float val1;
double val2;
val1 = atof(test);
val2 = atof(test);
return 0;
}
I expect the obvious result of 0 to the float variable as well, but it keeps getting the fixed 2 value.
UPDATE:
This code section is part of a much bigger project and there is no point in elaborating on the project. I have custom Makefile with LDFLAG option
"-mfloat-abi=hard -mfpu=fpv4-sp-d16 -u _printf_float".
Could this affect this issue?
As the MCV example is concerned, in main.c I have the above code section and I got the results mentioned.
Can anybody think of any reason atof() behaves in this way?
Of course I have used online c compiler as well with the exact same code and the result is of course 0. I guess if something was very very wrong with the stdlib library, then atof() would not work for all the other cases as well. But it fails only for "0" and only with the result 2 assigned to the float variable.
I watch the variables realtime with Ozone debugger software.
Could the reason be the floating point implementation on STM32F4 mcu used? A missing parameter in the custom Makefile or something like that?
First, your question lacks a Minimal, Complete, and Verifiable example.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char test[] = "0";
float val1;
double val2;
val1 = atof(test);
printf("%f\n", val1);
val2 = atof(test);
printf("%f\n", val2);
}
Output:
0.000000
0.000000
<°)))<()
Or your standard library implementation is fubar.
It looks like the cause of your problem is in the updated question text:
UPDATE: This code section is part of a much bigger project and there is no point in elaborating on the project. I have custom Makefile with LDFLAG option
"-mfloat-abi=hard -mfpu=fpv4-sp-d16 -u _printf_float".
Assuming these options are changes vs the defaults, what you're doing is telling the compiler to generate code for a different ABI from your toolchain's library ecosystem. The code generated for main expects the result of atof in a floating point register, but atof is using the standard ABI, which passes floating point arguments and return values in general-purpose registers. Thus, main is just reading whatever junk happens to be left in the floating point registers used for return values.
See if your problem goes away if you remove -mfloat-abi=hard. If so, you've probably found your problem. You need to either build a toolchain and libraries for the hardfloat ABI, or stick with the default non-hardfloat calling convention.
I'm new to coding in C so im sure this is a basic question. in my mind, this code should read an input, run the rcall() which does nothing, and output the same value. This works perfectly with int() values, but as soon as I switch to double, the output doesn't change from -6158. How do fix this logic error?
double input, output, rcall(x);
int main(void){
scanf("%lf", &input); /*read the input*/
output=rcall( input); /*call the function*/
printf("%lf", output); /*print the output*/
}
double rcall(x){ /*this function does nothing*/
return x;
}
The problem here is that you are using a 17 year old compiler, or have your current compiler incorrectly configured to compile the code as if it was older than 17 years.
The declaration double rcall(x); is nonsense in modern C.
But ancient C allowed sloppy declarations where not all types were specified, or even allowed you to call functions that had no declaration. The compiler would then always "helpfully" assume that those types that weren't explicitly specified are all int. If it turned out that they actually weren't, your program would then crash and burn.
This sheer stupid system was removed from the C language in the year 1999, with the "C99" standard. In modern C, your declaration should be
double rcall (double x);
and the definition should be
double rcall (double x)
{
return x;
}
In case you are using GCC, you can configure it to correct code according to modern standard C by adding the options gcc -std=c11 -pedantic-errors. Then you would have gotten a compiler error for the original code.
Declare x as a double type
double rcall(double x)
I've got a function that takes a matrix of velocities for a bunch of particles and tries to calculate the total kinetic energy of the particles.
It doesn't give me the right value. In order to debug, I added a few printf("value: %e \n", energy) in the function.
And now, the return value depends on how many of these printfs I leave uncommented.
double GetKineticEnergy(int dim, int nParticles, double vel[nParticles][dim], double mass)
{
int i,j;
double sum;
double energy = 0;
for(i=0;i<nParticles;i++) {
sum = 0;
for(j=0;j<dim;j++) {
sum += vel[i][j]*vel[i][j];
}
energy += sum*mass/2;
// printf("energy: %e \n", energy);
}
// printf("total: %e \n", energy);
return(energy);
}
and right after returning to the caller I print the returned value. I get 18.0, 19.0, 21.0, or 24.0, depending on which combination of the printfs I uncomment.
What am I doing wrong?
Update:
In trying to troubleshoot this, I've commented out pretty much everything. The function is reduced to
{
double energy = 123;
return(energy);
}
and the main program is
int main() {
double a;
double vel[5][5];
a = GetKineticEnergy(1, 1, vel, 1);
printf("value: %e \n", a);
}
and I get
value: 0.000000e+00
as output.
Update:
The problem goes away if I hardcode the second dimension of the 2D array double vel[][3]. For the time being, this seems like a useful fix, but I cringe at that type of hardcoding.
It can happen if GetKineticEnergy function is in a different file and prototype is not available. Consider declaring its prototype in main or include required header file.
You have invoked undefined behaviour.
When you are faced with seemingly inexplicable behaviour from a C program, it is typically the result of undefined behaviour. Here are a few potential problems that you should look into:
Compiler warnings
Compilers usually omit many important warning messages by default, and you have to enable those yourself. Compiling with optimizations enabled can also activate some additional warning messages due to the added code analysis. If you're using GCC, you should at a minimum use something like gcc -ansi -pedantic -W -Wall -O2.
Function prototypes
Have you provided correct function declarations (with prototypes) for all the functions in your code? Without a correct declaration of GetKineticEnergy(), the compiler will pass the last argument as int and assume that the return type is int.
Did you #include <stdio.h>? printf() is a variadic function. Variadic functions usually require different calling conventions than normal functions. Calling a variadic function without the correct prototype causes undefined behaviour.
Buffer overflow
Did you allocate enough memory, or specify a large enough size, for the array passed to the function? Are you passing the correct dimensions? Accessing elements beyond the limits of a buffer can cause perplexing results, especially with optimizations enabled.
I came across an interesting output and I'd to know how the computer is working to produce this. I know that whenever you have %d in a string, you should have a variable to accompany it. When I wrote two %d's and only one variable, I expected that the computer would churn out the same value for the %d's, since it had only one variable to draw on, but for some reason, the %d's returned the value for x and the value for the variable xCubed. I want to know why the program returns xCubed without my writing xCubed at the end of the string. Here's the code:
#include <stdio.h>
int cube(int x);
int main(void){
int x = 5;
int xCubed = cube(x);
printf("Why does this number, %d, equal this number %d?", x);
return 0;
}
int cube(int x){
return x * x * x;
}
Thank you!
Your program invokes undefined behaviour. Anything could happen. Possibly the valued returned from the call to cube happens to lie next to the value of x on the stack. Of course, this behaviour being undefined means that any change to your program, or your compiler options, could result in different behaviour.
In any case, you are expected to supply two values. Do so.
printf("Why does this number, %d, equal this number %d?", x, x);
If you compiled your program with full warnings then the compiler would have warned you of your error. And you could even ask your compiler to treat warnings as errors to stop you committing the mistake.
Your program causes undefined behaviour, so anything is possible. It's some quirk of stack/register layout and calling convention for your platform that gives you the results you see.
That is because xCubed happens to be allocated just after x, which means closer to the printf part of the stack (activation frame).
printf is a vararg function, it has no implicit way of knowing how many arguments it was passed. So, when you call printf with two placeholders but just one value supplied, it will read past the first argument expecting a second and "fall" into the stack of the caller, whose nearest content is exactly xCubed.
Just to be clear: this is the reason why your code exhibits that particular behaviour, not the way it is expected to work. You have a serious bug in your code.
This was by good luck. In effect, it is undefined behaviour.
Obviously, in your case the variable xCubed was put onto stack immediately after the free space. Upon doing the printf() call, x was put immediately before that, and then the address of the format string.
If you compile this program with other optimization settings, your compiler might decide to put xCubed somwhere else, or in a register, or omit it altogether, as its value is never used.
I came across this program via a quora answer
#include<stdio.h>
int main() {
printf("%d\n", ( { int n; scanf("%d", &n); n*n; } ));
return 0;
}
I was wondering how does this work and if this conforms the standard?
This code is using a "GNU C" feature called statement-expressions, whereby a parentheses-enclosed compound statement can be used as an expression, whose type and value match the result of the last statement in the compound statement. This is not syntactically valid C, but a GCC feature (also adopted by some other compilers) that was added presumably because it was deemed important for writing macros which do not evaluate their arguments more than once.
You should be aware of what it is and what it does in case you encounter it in code you have to read, but I would avoid using it yourself. It's confusing, unnecessary, and non-standard. The same thing can almost always be achieved portably with static inline functions.
I don't believe it does work... n has local scope within the braces... when you exit the braces, n becomes undefined though I suppose is could still exist somewhere on the stack and might work. It's begging for implementation issues and I guarantee is implementation dependent.
One thing I can tell you is that anyone working for me who wrote that would be read the riot act.
It works. I get no warnings from gcc, so I suppose that it conforms to the standard.
The magic is the closure:
{ int n; scanf("%d", &n); n*n; }
This nugget scans an integer from the console (with no error checking) and squares it, returning the squared number. In ancient implementations of C, the last number on the stack is returned. The n*n puts the number on the stack.
That value gets passed to the printf:
printf("%d\n", <scanned>);
So, to answer your questions: Yes, it works. Yes, it's "standard" (to the extent that anyone follows the standard entirely). No, it's not a great practice. This is a good example of what I by knee-jerk reaction call a "compiler love letter", designed mostly to show how smart the programmer is, not necessarily to solve a problem or be efficient.