Unexpected behavior from beginner C program - c

I am working to learn about computing at a more granular level and have started studying both Linux and C at the same time. Smooth sailing until just now.
I am running Linux Mint 17 on Kernel 3.16.0-38-generic and using Code::Blocks 13.12 as my IDE.
The following pastes are my practice code using data types, variables, and printf(), and the associated output I see in a vt -- the oddity I see is that on my experimentation with decimal places using the float data type, it seems to be skipping values after the 5th and eventually 4th decimal place.
Am I abusing the process of calling a variable, am I missing a bug in my code, or is this a bug in CodeBlocks? Also -- I'm not sure why my code snippet is completely mashed together in the preview, so my apologies for the poor readability
code to be compiled and executed:
/* Prints a message on the screen */
#include <stdio.h>
echar a1 = 'a';
int i1 = 1;
float f1 = 0.123456;
int main()
{
printf("Testing %c la%sof characters using variables \n", a1, "rge string " );
printf("This line has the values %d and %f.\n", i1, f1);
printf("%f can also be displayed as %.5f or %.4f or %.3f or %.2f or %.1f or %.0f \n",
f1, f1, f1, f1, f1, f1, f1);
printf("Which is an integer . . .");
return 0;
}
output of compiled and executed code
Testing a large string of characters using variables
This line has the values 1 and 0.123456.
0.123456 can also be displayed as 0.12346 or 0.1235 or 0.123 or 0.12 or 0.1 or 0
Which is an integer . . .
Process returned 0 (0x0) execution time : 0.002 s
Press ENTER to continue.
Thank you for any help you can provide. I am studying from C Programming Absolute Beginner - by Greg Perry

As was mentioned in the comments, the last digit is being rounded.
If you had this:
float f1 = 0.777777;
The output would be this:
This line has the values 1 and 0.777777.
0.777777 can also be displayed as 0.77778 or 0.7778 or 0.778 or 0.78 or 0.8 or 1
Similarly, if you had this:
float f1 = 0.999888;
You'd get this:
This line has the values 1 and 0.999888.
0.999888 can also be displayed as 0.99989 or 0.9999 or 1.000 or 1.00 or 1.0 or 1

Related

In what situation the output could go wrong like this?

I am trying to do the problem 200B on codeforces. I tested my code, and the output was all right. But when I uploaded it to the online judge system, I failed on the very first test case. It said my output was -0.000000000000, instead of 66.666666666667.
But I have compiled and run on Visual Studio C++ 2010, MacOS clang 13.0.0, and Linux GCC 6.3.0, the outputs were all the same as mine, 66.666666666667. I am very curious and want to figure out in what situation the output could be -0.000000000000.
On my computer,
Input:
3
50 50 100
Output:
66.666666666667
On the online judge system,
Input:
3
50 50 100
Participant's output
-0.000000000000
Jury's answer
66.666666666667
Checker comment
wrong answer 1st numbers differ - expected: '66.66667', found: '-0.00000', error = '1.00000'
#include <stdio.h>
int main(void)
{
int n;
double sumOrange = 0;
double sumDrink = 0;
scanf ("%d", &n);
while (n-- > 0) {
int m;
scanf("%d", &m);
sumOrange += m / 100.0;
sumDrink++;
}
printf("%.12lf\n", (sumOrange / sumDrink) * 100.0);
return 0;
}
I just don't understand why my output could be -0.000000000000. Please help, thanks.
Update: Tested on different versions of GCC (4.9, 5.1, 6.3), the wrong output does not appear. Guess the cause might lie in the specific implementation of printf.
The problem is because printf function in GNU gcc C11 does not support %.12lf format. It should be changed to %.12f For more information, you can read the article below:
Correct format specifier for double in printf

Q: About reading data files using fscanf()

Am using Turbo C in a DOS emulator (Dosbox). In the following lines, I am trying to read integer and float data but only get the first (int) field. Have found much Q & A on the subject of reading files using fscanf() and, specifically, with space-delimited data but relevant info was scant or missing (mostly from the questions). Here is code demonstrating the problem:
#include <stdio.h>
int index;
float rtime, volts;
char infilename[10];
int *pti;
float *ptx;
float *pty;
FILE *infp;
void main(void)
{
infp = fopen("data1", "r");
pti = &index;
ptx = &rtime;
pty = &volts;
fscanf(infp, "%d %6.3f %6.3f", &index, &rtime, &volts);
printf("%3d %6.3f %6.3f\n", index, rtime, volts);
}
Here is the first line from the data file:
37 261.100 0.996
printf gives the following output:
37 0.000 0.000
Any obvious goofs? thx
The format %6.3f is incorrect for scanf(). You probably want %f, or possibly %7f. You cannot specify the number of decimals in a scanf() format.

Do not understand message received after running temperature convert program

I am new to C and trying to write a program using Xcode that takes the temperature in Fahrenheit and converts it to Celsius, and vise versa. My code so far is below.
#include <stdio.h>
#include "hw2.h"
void convert_temp(int degree1, char scale1, int* degree2, char* scale2){
if (scale1 == 'F') {
*degree2 = ((degree1 - 32) * 5) / 9;
*scale2 = 'C';
}
else {
*degree2 = ((degree1 * 9) / 5) + 32;
*scale2 = 'F';
}
}
int main() {
int degree1, degree2;
char scale1, scale2;
printf("Enter a temperature and a scale\n");
scanf("%d %c", &degree1, &scale1);
convert_temp(degree1, scale1, &degree2, &scale2);
printf("%d %c = %d %c\n", degree1, scale1, degree2, scale2);
return 0;
}
Here is an example of correct i/o:
Enter a temperature and a scale
32 F
32 F = 0 C
However, when I run the code, this is what I get:
Enter a temperature and a scale
32 F
hw2 was compiled with optimization - stepping may behave oddly; variables may not be available.
(lldb)
I cannot understand the output I am getting. Can anybody tell me why I do not get 32 F = 0 C on my output? Everything in my code seems fine to me.
Assuming hw2 is the name of your program, then the debugger is complaining that it was compiled with optimisations turned on, which isn't normal during development, as the optimizer does all sorts of clever things to get the program running faster.
You need to do the following in Xcode:
Ensure you are debugging using the Debug build configuration (Check your Schemes).
Ensure you haven't turned on Optimizations for the Debug build configuration (Check your Build Settings).

cblas_dgemm - works ONLY if (beta) is power-of-two

I am totally stumped. I have a fairly large recursive program written in c that calls cblas_dgemm(). The result is verified independently by a program that works correctly.
C = alpha*A*B + beta*C
On repeated tests using random matrices and all possible combination of parameters the program gives correct answer ONLY if abs(beta) = 2^n (1,2,4,8..). Any value works for alpha. Any other positive/negative, odd/even value for beta gives correct answer b/w 10-30% of the time.
I am using Ubuntu 10.04, GCC 4.4.x, I have tried system installed blas/cblas/atlas as well as manually compiled atlas.
Any hints or suggestions would be greatly appreciated. I am amazed at the wonderfully generous (and smart) folks lurking at this site.
Thanking you all in advance,
Russ
Two completely unrelated errors conspired to produce an illusive picture. It made me look for problems in the wrong place.
(1) There was a simple error in the logic of the function calling dgemm. Would have been easily fixed if I was not chasing the wrong problem.
(2) My double-compare function: double version of AlmostEqual2sComplement() (http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm) used incorrect sized integer - resulting in an incorrect TRUE under certain rare circumstances. This was the first time the error bit me!
Thanks again for the useful suggestion of using the scientific method when trying to debug a program.
Russ
Yes, a full example would be handy. Here is an old example I had hanging around using GSL's sgemm variant; should be easy to fix to double. Please try and see if this gives the result shown in the GSL manual:
/* from the gsl info documentation in node 'gsl cblas examples' */
/* compile via 'gcc -o $file $file.c -lgslcblas' */
/* edd 15 Nov 2003 */
#include <stdio.h>
#include <gsl/gsl_cblas.h>
int
main (void)
{
int lda = 3;
float A[] = { 0.11, 0.12, 0.13,
0.21, 0.22, 0.23 };
int ldb = 2;
float B[] = { 1011, 1012,
1021, 1022,
1031, 1032 };
int ldc = 2;
float C[] = { 0.00, 0.00,
0.00, 0.00 };
/* Compute C = A B */
cblas_sgemm (CblasRowMajor,
CblasNoTrans, CblasNoTrans, 2, 2, 3,
1.0, A, lda, B, ldb, 0.0, C, ldc);
printf ("[ %g, %g\n", C[0], C[1]);
printf (" %g, %g ]\n", C[2], C[3]);
return 0;
}

Stuck as a Beginner: C Programming

I am taking a C programming class this semester, and was somehow allowed to register despite not fulfilling the prerequisite. I thought I would still be able to handle it, but now that I have passed the point of no return for dropping it, I find myself completely lost.
For my current assignment, I am supposed to create a program that does a few simple trig operations and display the results. The main idea is that there is a building, and I am standing a certain distance from it.
For part A, I have to calculate the height of the building assuming I am standing 120 meters from the building and am looking at the top while tilting my head at a 30 degree angle (plus/minus 3 degrees).
Part B, assumes the building is 200ft tall, and I am standing 20ft away. What would be the angle I would have to tilt my head to see the top?
Part C, given the info in part B, how far is the distance (hypotenuse) from my head to the top of the building?
So far, I have written this:
#include <stdio.h>
#include <math.h>
#define MAX_ANGLE 33
#define MIN_ANGLE 27
#define DIST_A 120
#define DIST_B 20
#define HEIGHT_B 200
#define PI 3.14159
int main()
(
double MIN_ANGLE_R, MAX_ANGLE_R;
MIN_ANGLE_R = MIN_ANGLE * (PI / 180);
MAX_ANGLE_R = MAX_ANGLE * (PI / 180);
min_height = DIST_A * tan(MIN_ANGLE);
max_height = DIST_A * tan(MAX_ANGLE);
angle = atan(HEIGHT_B/DIST_B)/(PI/180);
hypotenuse = HEIGHT_B/tan(angle);
printf ("The minimum height is %6.2f meters.\nThe maximum height is%6.2f meters.\n\n",min_height,max_height);
printf ("The angle that youw ill tilt your head to see\nthe top of the building is %3.2f feet.\n",angle);
printf ("The distance from your head to the top of the building is %6.2f feet.\n",hypotenuse);
return 0;
)
When I try compiling the program, I keep getting errors that I don't know how to read. IF anyone could read through my program, and tell me what's missing, it would be a huge help.
Don't confuse () and {}. They mean different things.
Declare your variables.
You have to open and close main() with "{ ... }" instead of "( ... )". Also, you have to declare all the variables you are using (not just MIN_ANGLE_R and MAX_ANGLE_R).
I'm not a C programmer, but I suspect your trig functions work in radians and you seem to be passing degrees.

Resources