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
Related
The program must accept an integer N with even number of digits as the input.
The program must reverse every two digits in N and print the modified N as the output.
Boundary Condition(s): 10 <= N < 10^16
Input Format: The first line contains N.
Output Format: The first line contains the modified N.
Example Input/Output 1:
Input: 214587
Output: 125478
Explanation: The first two digits are 2 and 1 which are reversed as 1 and 2. The second two digits are 4 and 5 which are reversed as 5 and 4. The third two digits are 8 and 7 which are reversed as 7 and 8.
Example Input/Output 2:
Input: 504786
Output: 57468
I have proceeded in a logic of printing the values inside a while loop by printing b/10 and b%10; where the output should be reversed and I am stuck in it, please help in my logic how to proceed further thank you.
scanf("%d",&a);
while(a>0) {
b=a%100;
printf("%d%d",b/10,b%10);
a=a/100;
}
As I noted in three comments (1, 2, 3), I think you need to use recursion, and some care. Here is code that works, and a test harness (which is bigger than the code being tested) demonstrating that it works:
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static bool reverse_digit_pairs(uint64_t value)
{
uint64_t b = value % 100;
uint64_t v = value / 100;
if ((v > 0 && v < 10) || (v == 0 && b < 10))
return false;
int t = b / 10; // tens
int u = b % 10; // units
bool ok = true;
if (v >= 10)
ok = reverse_digit_pairs(v);
if (ok)
{
if (u == 0 && v == 0)
printf("%d", t);
else
printf("%d%d", u, t);
}
return ok;
}
static void test_reverse_digit_pairs(uint64_t v)
{
printf("V: %20" PRIu64 " = ", v);
if (!reverse_digit_pairs(v))
{
fprintf(stderr, "Odd number of digits in %" PRIu64 "\n", v);
printf("bogus input");
}
putchar('\n');
fflush(0); // Ensure standard output (and standard error) are flushed.
}
int main(void)
{
test_reverse_digit_pairs(UINT64_C(214587)); // 125478 per question
test_reverse_digit_pairs(UINT64_C(504786)); // 57468 per question
test_reverse_digit_pairs(UINT64_C(5047000086)); // Pairs of zeros
test_reverse_digit_pairs(UINT64_C(5047900086)); // Pair of zeros
test_reverse_digit_pairs(UINT64_C(1234567890123456)); // 16 digits
test_reverse_digit_pairs(UINT64_MAX); // 20 digits
test_reverse_digit_pairs(UINT64_C(123456789012345)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(0)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(1)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(9)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(10)); // 2 digits
test_reverse_digit_pairs(UINT64_C(99)); // 2 digits
test_reverse_digit_pairs(UINT64_C(100)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(999)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(1000)); // 4 digits
test_reverse_digit_pairs(UINT64_C(1098)); // 4 digits
test_reverse_digit_pairs(UINT64_C(1234)); // 4 digits
return 0;
}
The output I get from it is:
V: 214587 = 125478
V: 504786 = 57468
V: 5047000086 = 574000068
V: 5047900086 = 574090068
V: 1234567890123456 = 2143658709214365
V: 18446744073709551615 = 81447644707390556151
Odd number of digits in 123456789012345
V: 123456789012345 = bogus input
Odd number of digits in 0
V: 0 = bogus input
Odd number of digits in 1
V: 1 = bogus input
Odd number of digits in 9
V: 9 = bogus input
V: 10 = 1
V: 99 = 99
Odd number of digits in 100
V: 100 = bogus input
Odd number of digits in 999
V: 999 = bogus input
V: 1000 = 100
V: 1098 = 189
V: 1234 = 2143
The test cases for the numbers with 1 to 4 digits were necessary to flush out some issues. I'm not completely happy with the first condition in reverse_digit_pairs(), but I didn't get the output I think is required when I tried some simplifications.
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.
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
#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);
I m trying to find number of factors of product of big numbers.
The problem statement is this : Suppose you are given N numbers(let say N = 10), each number <= 1000000.
How to find the number of factors of the product of such numbers.
Can someone please provide an efficient algorithm for doing this.
Example :
1) N = 3 and Numbers are 3, 5, 7
Ans = 8 (1, 3, 5, 7, 15, 21, 35, 105)
2) N = 2 and Numbers are 5, 5
Ans = 3 (1, 5 and 25)
Editorial for the problem is here
http://discuss.codechef.com/questions/15943/numfact-editorial
int total = 0, N = 0, Number;
scanf ("%d", &total);
while (total--)
{
scanf ("%d", &N);
map<int, int> Counter;
for (int i = 0; i < N; i++)
{
scanf ("%d", &Number);
for (int j = 2; j * j <= Number; j++)
{
while (Number % j == 0)
{
Counter[j]++;
Number /= j;
}
}
if (Number > 1) Counter[Number]++;
}
int Answer = 1;
for (map<int, int>::iterator it = Counter.begin(); it != Counter.end(); it++)
Answer *= (it->second + 1);
printf ("%d\n", Answer);
}
This got Accepted.
Sample Inputs and Outputs:
7
3
3 5 7
3
2 4 6
2
5 5
10
2 2 2 2 2 2 2 2 2 2
1
100
10
10000 10000 10000 10000 10000 10000 10000 10000 10000 10000
10
1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000 1000000
8
10
3
11
9
1681
3721
Factorize each number into list of prime factors and their multiplicities, L(n) = { p_i , k_i }, for a number n = Π piki. Numer of divisors for such n is ND( L(n) ) = Π (ki+1) a product of all coefficients, each incremented by 1 (this includes 1 and n itself as divisors of n). This corresponds to picking none, one, ... ki of each of them to multiply.
To calculate the ND of a product of arbitrary number of numbers, factorize each and merge their factorizations, where in case of matching primes their coefficients are added together. Then calculate the ND of the merged factorization.
To merge many factorizations together, start by merging two of them; then merge the result and the next one; then merge the last result and the next factorization, and so on. This is called folding. Or better merge them pairwise, then merge the results in same pairwise fashion, and so on util only one merged result is left. That's similar to how a bottom-up mergesort is done.
Multiply all the numbers, factorize the result, count all divisors:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
int p = 1;
for (int i = 1; i < argc; i++)
p *= strtol(argv[i], NULL, 10);
int n = 0;
int s = sqrt(p) + 1;
for (int i = 1; i <= s; i++)
if (p % i == 0)
n += 2 - (p / i == i); // obfuscation ;)
printf("%d\n", n);
return 0;
}