can you write a program whose output is like this:
How many coins are flipped? 3
HHH
HHT
HTH
HTT
THH
THT
TTH
TTT
the program is all about tossing coin/s (probability), also known as Head and Tail.
it ask the user of how many coins then it prints the outcomes.
the formula for number of outcomes is 2^n (where n is the number of coins).
C Programmer...help(I'll give my 10 points for good answer)?
#include %26lt;math.h%26gt;
void printcorrespondinghandt(int i,int num);
void main()
{
int i;
int num = 3;
for(i=0;i%26lt;pow(2,num);i++)
{
printcorrespondinghandt(i,num);
printf("\n");
}
}
void printcorrespondinghandt(int i,int num)
{
int j;
for(j=0;j%26lt;num;j++)
{
if((i%26gt;%26gt;j)%26amp;0x1)
printf("h");
else
printf("t");
}
}
Reply:umm.. i am not gonna code this for you, but there is an easy way to look at this.
Basically given n coins, you can only get 2^n output.
Assume H=1 and T=0, then it looks like
for(i=0;i%26lt;2^n-1;i++)
print binary representation of i, replacing 1s with H and 0s with T
Reply:#include %26lt;iostream%26gt;
#include %26lt;windows.h%26gt;
using std::cin;
using std::cout;
using std::endl;
inline char* createPattern(char%26amp;, char%26amp;, int%26amp;, int%26amp;);
int main() {
char head = 'H';
char tail = 'T';
int n;
cout %26lt;%26lt; "#of coins= "; cin %26gt;%26gt; n;
for (int i = 1 %26lt;%26lt; n; --i %26gt;= 0;) { //1 %26lt;%26lt; n = pow(2, n)
cout %26lt;%26lt; createPattern(head, tail, i, n) %26lt;%26lt; endl;
}
system("PAUSE"); //calls MS-DOS pause command
return 0;
}
inline char* createPattern(char%26amp; h, char%26amp; t, int%26amp; i, int%26amp; n) {
char *c = new char[n];
for (int x = n, j = 0; --x %26gt;= 0;) {
c[j++] = (i %26amp; (0x1 %26lt;%26lt; x)) == 0 ? t : h;
}
return c;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment