What's wrong with this C program [duplicate]
Possible Duplicate:
Help with C puzzle
The intention of the program was to print a minus sign 20 times, but it doesn't work.
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 开发者_StackOverflow中文版0; i < n; i-- )
printf("-");
return 0;
}
This is a classic puzzle!
The way I saw it was
"You can only change/insert/delete one character in the code to make the - print 20 times".
Some answers are (if I remember them correctly)
1)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; -i < n; i-- )
printf("-");
return 0;
}
Here you change the i < n
to -i < n
2)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; n-- )
printf("-");
return 0;
}
Here you change the i--
to n--
3)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i + n; i-- )
printf("-");
return 0;
}
You change the i < n
to i+n
.
For a challenge, try changing/inserting/deleting one character to make it print the - 21 times. (Don't read the comments to this answer if you want to try it!)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; i++ )
printf("-");
return 0;
}
You had --
instead of ++
Replace i-- with i++.
int main() {
int i;
int n = 20;
for( i = 0; i < n; i++)
printf("-");
return 0;
}
You had decrement instead of increment.
Have you tried changing the
i--
to
i++
You have the loop to print out a "-" for as long as "i" is less than 20. After every loop you reduce the value of i by 1, it will continue to print for a very long time. Changing the final part of the for loop to "i++" means it will perform one iteration each loop and stop once the twentieth iteration finished.
Change i-- to i++. i-- decrements the value which at start is 0 and with subsequent reductions won't ever reach 20 (or +20).
the i-- needs to be i++
you could also do
int n = -20;
for( i = 0; i > n; i-- )
but that is bad coding practice
What exactly are you trying to do with this problem???
Here you are trying to decrement the value of a variable..a variable whose value will never reach the condition (i<20) you have provided... hence it will keep on printing '-' until what jamie wong specified, i.e. i= -2^31
. It will become +ve. I just tried this program.
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; i-- )
printf("-");
return 0;
}
According to the question you asked, i
should be incremented, i.e. i++
instead of i--
.
@jamie wong: thanx man..learnt a new thing about tht a wraparound....
You'll print no dashes. You can either go with Jaime Wong's solution or do this:
for (i = n; i >= 0; i--)
精彩评论