GCC division truncates (rounding problem) - c

Using GCC on the Ubuntu Linux 10.04, I have unwanted rounding after a division.
I tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void FormatReading(int temp)
{
double reading = temp / 100;
printf("%f\n",reading); /* displays 226.000000, was expecting 226.60 */
}
int main(void)
{
FormatReading(22660);
return 0;
}
It was suggested to me to try:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void FormatReading(int temp)
{
long reading = temp ;
reading = reading / 100;
printf("%3.2ld\n",reading); /* displays 226 */
}
int main(void)
{
FormatReading(22660);
return 0;
}
I also tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void FormatReading(int temp)
{
long reading = temp ;
double reading2 = reading / 100;
printf("%3.2f\n",reading2); /* displays 226.00 */
}
int main(void)
{
FormatReading(22660);
return 0;
}
I also tried the round function using include math.h with compiler tag -lm in various ways, but did not find what I was looking for.
Any help greatly appreciated.
Best regards,
Bert

double reading = temp / 100.0;
^^
temp / 100 is an integer division - that you assign the result to a double doesn't change this.

You are using integer division which always gives integral results rather than fractions, and then the result is being assigned to a double. Divide by 100.0 instead of 100 to get the behavior you want.

Related

Why it isn't working? I have seen examples using this, but when I use it, it crashes. Why?(C)

Why can't I do g->n=n ? Can someone explain?
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX 100000
int N[]={100,200,300,400,500,600,700,800,900,1000};
double B[]={0.125, 0.250, 0.375, 0.5, 0.625, 0.750, 0.875};
typedef struct Graph
{
int n;
int M[MAX][MAX];
int val;
int adjacent[MAX-1];
}G;
struct Graph * RandomDirectedGraph(int n, double b)
{
struct Graph * g = (struct Graph*)malloc(sizeof(struct Graph));
g->n=n;
int u,i,v;
for(u=0;u<n;u++)
{
for(i=0;i<n;i++)
{
g->M[u][i]=0;
}
}
int m=b*n*n;
for(i=0;i<m;i++)
{
do
{
u=rand()%n;
v=rand()%n;
}
while(u==v || g->M[u][v]==1);
g->M[u][v]=1;
}
};
int main()
{
int i,j,n,b;
for(i=0;i<sizeof(N)/sizeof(*N);i++)
{
for(j=0;j<sizeof(B)/sizeof(*B);j++)
{
RandomDirectedGraph(N[i],B[j]);
}
}
return 0;
}
When I compile and run it, ERROR pops up and says that some memory can't be written. I don't know what I'm doing wrong here.
The issue is that everytime you are executing the method RandomDirectedGraph, your application tries to reserve about 40GB of RAM memory. I guess your computer doesn't have that much.
Furthermore you should release all memory by calling free on the pointers.
For such big matrices, you don't use classic C matrices. You need external librarys for sparse matrix calculations like https://www.alglib.net/matrixops/sparse.php

I am using this code to print from text file but the program gives me "-1.#IND00"

I have a problem. I am using this code to print from text file but the program gives me a different number -such as 11732408.000000- each time. However I don't get this problem when ex is integer.
#include <stdio.h>
#include <string.h>
int main() {
char example[] ="123.12/456 ";
double ex = atof(strtok(example, "/"));
printf("%lf", ex);
return 0;
}
I could solve my problem. Thank you for your helps.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char example[20] ="123.12/456 ";
double ex=atof(strtok(example,"/"));
printf("%lf",ex);
return 0;
}
You forgot to include <stdlib.h> which contains the declaration of atof().
Your compiler is lenient and accepts your code is spite of the missing declaration, and it incorrectly infers the prototype to be int atof(char *), which causes undefined behavior when storing the return value to ex.
Hence the bogus output.
Note also that the l in the format %lf is necessary for scanf() but ignored by printf() as float arguments are implicitly converted to double when passed to vararg functions.
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char example[] = "123.12/456 ";
char *p = strtok(example, "/");
if (p != NULL) {
double ex = atof(p);
printf("%f\n", ex);
}
return 0;
}

print result using system calls

For my OS class, I need to print out the result of this matrix multiplication using only system calls. Following my lecture notes, I wrote up this piece of code. I use :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 1000
// Matrix
long long int A[N][N],B[N][N],R[N][N];
int main(int argc, char *argv[])
{
int x,y,z;
char str[100];
/* Matrix inicialization */
for(y=0;y<N;y++)
for(x=0;x<N;x++)
{
A[y][x]=x;
B[y][x]=y;
R[y][x]=0;
}
/* Matrix multiplication */
for(y=0;y<N;y++)
for(z=0;z<N;z++)
for(x=0;x<N;x++)
{
R[y][x]+= A[y][z] * B[z][x];
}
//System calls for printing the result
sprintf(str,"%lld\n",R);
write(1,str,strlen(str));
exit(0);
}
Now, it's printing a just a 14295680 in the console. The professor gave us a file with machine code and it's printing 332833500, which seems more reasoneable.
Thanks in advance.
Edit: changed type on the printf call
Edit2: fix R[N][N]
Just replace the sprintf value:
sprintf(str,"%lld\n",R[N-1][N-1]); // = 332833500
write(1,str,strlen(str));
instead of
sprintf(str,"%lld\n",R); // this is a pointer
write(1,str,strlen(str));

How to use DBL_MANT_DIG to check strtod

Consider the following code:
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <errno.h>
#include <float.h>
int main (void) {
double val;
/* base b = 2; 2^DBL_MANT_DIG */
/* decimal digits log10(2^DBL_MANT_DIG) */
/*const char *str = "9007199254740992";*/
const char *str = "9007199254740993";
errno = 0;
val = strtod(str, NULL);
printf("%d\n", DBL_MANT_DIG );
if (errno == ERANGE) {
printf("error\n");
} else {
printf("%f\n", val);
}
return 0;
}
This returns:
53
9007199254740992.000000
Since str has a string number that has more significant digits than the my machine can handle, how does one use DBL_MANT_DIG or the log10(2^DBL_MANT_DIG) version of it to check that the result of val is correct?
You don't use those to check that the conversion is exact.
Here's one way of how to do it.
Another way is to find out how many decimal digits after the decimal point are there in the resultant double, do sprintf() using that as the precision and compare its output with the original string.

character array to floating point conversion

I am trying to convert the output buffer(character array)
of the code below to floating point format for further calculations.
Can anybody tell me how to do it.
#include "usbtmc.h"
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <inttypes.h>
#include <sys/types.h>
#include <pthread.h>
int main()
{
int myfile;
char buffer[4000];
int actual;
myfile=open("/dev/usbtmc1",O_RDWR);
if(myfile>0)
{
system("echo MEAS:VOLT:AC?>/dev/usbtmc1");
actual=read(myfile,buffer,4000);
buffer[actual] = 0;
printf("Response = \n %s\n",buffer);
close(myfile);
}
return 0;
}
The sample output for this code is
Response =
+1.29273072E-04
You may have two ways:
using double atof(const char* str)
float f;
f = (float)atof(buffer);
printf("%f",f); // here you can use f
using int sscanf( const char * s, const char * format, ...)
float f;
sscanf(buffer,"%f",&f);
printf("%f",f); // here you can use f

Resources