Formatting help for command prompt output in C - c

#include <stdio.h>
#include <stdlib.h>
int power(int base, int power){
int result, i;
result = 1;
for (i=0; i < power; i++){
result *= base;
}/*for*/
return result;
}/*power*/
int main (){
int n = 0;
int exponent = 0;
while(n < 10){
int answer = power(2, n);
float neganswer = 1.0 / (power(2,n));
printf("%d %d %g\n", exponent, answer, neganswer);
exponent++;
n++;
}/*while*/
return EXIT_SUCCESS;
}/*main*/
When this program runs, the 2nd function goes from 1 to 512, which pushes the rest of the columns are moved 2 to the right. How would I go about lining up these columns? Thanks.

You can change your printf format to:
printf("%d %3d %10g\n", exponent, answer, neganswer);
This will format the argument to the specific width:
0 1 1
1 2 0.5
2 4 0.25
3 8 0.125
4 16 0.0625
5 32 0.03125
6 64 0.015625
7 128 0.0078125
8 256 0.00390625
9 512 0.00195312

Not to take away from the all ready provided fine 2 answers, but many options are available with printf().
// Nicely aligned with decimal point in the same place
// # : Alternate form always prints `.`
// - : Left justify the output.
// .* : Determine width from the next parameter which is `n`.
printf("%d %4d %#-.*f\n", exponent, answer, n, neganswer);
0 1 1.
1 2 0.5
2 4 0.25
3 8 0.125
4 16 0.0625
5 32 0.03125
6 64 0.015625
7 128 0.0078125
8 256 0.00390625
9 512 0.001953125

C string that contains the text to be written to stdout.
It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.
A format specifier follows this prototype: [see compatibility note below]
%[flags][width][.precision][length]specifier
int main (){
int n = 0;
int exponent = 0;
while(n < 10){
int answer = power(2, n);
float neganswer = 1.0 / (power(2,n));
//modify printf("%d %d %g\n", exponent, answer, neganswer);
printf("%d %4d %12g\n", exponent, answer, neganswer);
exponent++;
n++;
}/*while*/
return EXIT_SUCCESS;
}/*main*/
more about printf function, please refer to the following link
http://en.cppreference.com/w/c/io/fprintf

Take a look at my simple library: libtprint , the code there is quite easy to understand and you should get some basic ideas how to format columns with printf ().
Hope it helps !

Try this
float neganswer = 1.0f / (power(2,n));
printf("%d %3d %f\n", exponent, answer, neganswer);

Related

how do i use the for instruction in the proposed line of code?

who can assess here?
I need a step-by-step explanation of this program, in particular, I'm interested in this line of code:
for(i = n-((n+1) % 2); i>=1; i-=2)
#include <stdio.h>
int main()
{
int i, n;
scanf("%d",&n);
for(i = n-((n+1) % 2); i>=1; i-=2)
{
if(i%2==1)
printf("%d ", i);
}
return 0;
}
This expression
n-((n+1) % 2)
yields the closest odd number that is equal to or less than n.
For example if n is an even number for example is equal to 2 then the expression will be equal to the odd number 1.
That is you will have in this case
2 - ( ( 2 + 1 ) % 2 )
that is equivalent to
2 - ( 3 % 2 )
that in turn is equivalent to
2 - 1
If n is an odd number for example equal to 3 then the expression will be equal to 3.
So subtracting 2 as
i-=2
you will have always an odd number.
Thus this statement in the body of the for loop
if(i%2==1)
printf("%d ", i);
outputs positive odd numbers in the descending order.
For example if n is equal to 10 then i will be initially equal to 9 and the loop outputs
9 7 5 3 1
The if statement is redundant. You could just write
printf("%d ", i);

Creating an evenly spaced array of double precision values

I'm a noob in C and I come from Matlab. I'm going crazy to do a very simple operation like creating an array of evenly spaced numbers.
What I want to do is have an array of 50 elements, starting from 0 with a constant increment of 0.1.
In matlab it would be as simple as:
n=50;
h=0.1;
t=0:h:(n-1)*h;
In C I am trying this:
#include<stdio.h>
int main() {
int n = 50;
double h = 0.1;
double t[n];
t[0] = 0;
int i;
for (i = 0; i <= n; i++){
t[i+1] = t[i] + h;
printf("%i %d\n",i, t[i]);
}
return 0;
}
And the output is something crazy like:
0 0
1 -1717986918
2 -1717986918
3 858993460
4 -1717986918
5 0
6 858993459
7 1717986918
8 -1717986919
9 -858993460
10 -1
...
And I really can't understand why.
Thanks for your help!
In printf("%i %d\n",i, t[i]), t[i] is a double, but %d requires that you pass an int. Use %g for a general format for printing double.

Binary to decimal algorithm in c giving strange results

Hi i'm fairly new to c but for a program I'm writing I need to convert binary strings to decimal numbers. here is my current code:
int BinaryToInt(char *binaryString)
{
int decimal = 0;
int len = strlen(binaryString);
for(int i = 0; i < len; i++)
{
if(binaryString[i] == '1')
decimal += 2^((len - 1) - i);
printf("i is %i and dec is %i and the char is %c but the length is %i\n", i, decimal, binaryString[i], len);
}
return decimal;
}
int main(int argc, char **argv)
{
printf("%i", BinaryToInt("10000000"));
}
and here is the output:
i is 0 and dec is 5 and the char is 1 but the length is 8
i is 1 and dec is 5 and the char is 0 but the length is 8
i is 2 and dec is 5 and the char is 0 but the length is 8
i is 3 and dec is 5 and the char is 0 but the length is 8
i is 4 and dec is 5 and the char is 0 but the length is 8
i is 5 and dec is 5 and the char is 0 but the length is 8
i is 6 and dec is 5 and the char is 0 but the length is 8
i is 7 and dec is 5 and the char is 0 but the length is 8
5
I'm confused as to why this doesn't work, all help is greatly appreciated. Thanks in advance!
Ps: I'm used to java so at the moment C just makes me cry
The ^ operator is not for exponentiation, but is instead the bitwise XOR operator.
If you want to raise a number to a power of 2, use the left shift operator << to shift the value 1 by the exponent in question.
decimal += 1 << ((len - 1) - i);
The trick is the same as with any number base: for each incoming digit, multiply the accumulator by the number base and add the digit.
#include <stdio.h>
#include <string.h>
int BinaryToInt(char *binaryString)
{
int decimal = 0;
int len = strlen(binaryString);
for(int i = 0; i < len; i++) {
decimal = decimal * 2 + binaryString[i] - '0';
}
return decimal;
}
int main(void)
{
printf("%d", BinaryToInt("10000000"));
return 0;
}
Program output:
128

how to print a table of even squares?

This program prompts the user a number and then outputs a table of even squares ranging from 2 to the number.
#include <stdio.h>
int main(void)
{
int i, n;
puts(This program prints a table of even squares.);
printf("Enter range of the squares square: ");
scanf("%d", &n);
for (i = 2; i * i <= n; i += 2)
printf("%d\n", i * i);
return 0;
}
for example:
Enter range of the squares: 123
2 4
4 16
6 36
8 64
10 100
The problem is did not print 121 (which is 11 * 11). I am new to C and not really good in using loops. Please help!
for (i = 2; i * i <= n; i += 2)
You're starting at 2 and incrementing by 2. i will never be 11.

How do I format decimals in C?

This is my print statement:
printf("%d %f\n",kPower, raisePower);
This is my output:
-4 0.000100
-3 0.001000
-2 0.010000
-1 0.100000
0 1.000000
1 10.000000
2 100.000000
3 1000.000000
4 10000.000000
I want it to be printed like this:
UPDATE
So I made my positive values line up:
-4 0.0
-3 0.0
-2 0.0
-1 0.1
0 1.0
1 10.0
2 100.0
3 1000.0
4 10000.0
This is my new code so far:
printf("%d %10.1f\n",kPower, raisePower);
I don't know, should I make a for loop to print each one (positive results vs negative result) in a different format?
#include <stdio.h>
char *get_number_formatted(double f)
{
static char buf[128]; // this function is not thread-safe
int i, j;
i = snprintf(buf, 128, "%20.10f", f) - 2;
for (j = i - 8; i > j; --i)
if (buf[i] != '0')
break;
buf[i + 1] = '\0';
return buf;
}
int main(void)
{
int i;
for (i = -4; i < 5; ++i)
printf("%5d %s\n", i, get_number_formatted(pow(10.0, i)));
return 0;
}
http://ideone.com/KBiSu0
Output:
-4 0.0001
-3 0.001
-2 0.01
-1 0.1
0 1.0
1 10.0
2 100.0
3 1000.0
4 10000.0
printf() cannot print a variating length of decimal digits, so basically what I did was print the formatted number into a buffer and then cut the exceeding zeros.
Try calculating the powers first using pow() from math.h and then:
You can use %10f to precede the number with blanks in the example total of 10 spaces:
printf ("Preceding with blanks: %10f \n", 10000.01);
Source: cplusplus.com
Basicly you can use variable length to perform this:
printf("%d %.*lf", kPower, -kPower, raisePower);
Advantage over other methods is that this method does not need any extra buffer(s)
With a little help of modf, you can use %g to skip the trailing zeroes and \b to skip the leading zero:
#include <stdio.h>
#include <math.h>
int main(void)
{
int i, iarr[] = {-4, -3, -2, -1, 0, 1, 2, 3, 4};
double darr[] = {0.0001, 0.001, 0.01, 0.1, 1., 10., 100., 1000., 10000.};
double intpart, fractpart;
for (i = 0; i < 9; i++) {
fractpart = modf(darr[i], &intpart);
if (fractpart == 0.0)
printf("%10d%10d.0\n", iarr[i], (int)intpart);
else
printf("%10d%10d\b%g\n", iarr[i], (int)intpart, fractpart);
}
return 0;
}
Output:
-4 0.0001
-3 0.001
-2 0.01
-1 0.1
0 1.0
1 10.0
2 100.0
3 1000.0
4 10000.0
Try this example code
float y[7]={0.000100f,0.0010f,0.0100,0.1000f,1.0f,10.000f,100.00f};
int a[7]={-4,-3,-2,-1,0,1,2};
for(int i=0;i<7;i++)
printf("%2d%20f\n",a[i],y[i]);
Output will like that.
You can use sprintf and then trim the zeros. This is the same idea as #Havenard's answer, but writing spaces over the zeros instead of cutting the string.
And my C-style is somewhat different FWIW. My style is that I don't want to count or do any arithmetic in my head; that's what the C optimizer is for :).
#include <math.h>
#include <stdio.h>
#include <string.h>
int main() {
int kPower;
for(kPower=-4; kPower<5; kPower++){
enum { bufsize = 2+5+10+1+4+1+1 };
char buf[bufsize];
int j,n,i;
double raisePower = pow(10,kPower);
//printf("%2d %10.4f\n",kPower,raisePower);
snprintf(buf,bufsize,"%2d %10.4f\n",kPower,raisePower);
j=strchr(buf,'.')-buf;
j+=1;
n=strchr(buf+j,'\n')-buf;
for (i=n-1; i>j; i--)
if (buf[i]=='0')
buf[i]=' ';
else
break;
printf("%s",buf);
}
return 0;
}
Output:
-4 0.0001
-3 0.001
-2 0.01
-1 0.1
0 1.0
1 10.0
2 100.0
3 1000.0
4 10000.0
use printf like this:
printf( "%5d %10.1f\n",kPower, raisePower);
this will result in kPower being printed,
right justified,
in 5 columns
- sign in the right place
this will result in raisePower being printed with:
10 columns
leading 0s replaced by spaces
except 1 digit (could be 0) to the left of the decimal point
1 (rounded) digit to the right of the decimal point
- signs being printed at the proper location
decimal point being aligned

Resources