#include<stdio.h>
int main()
{
int i=10,a;
while(i>0)
{
scanf("%d",&a);
printf("%d\n"开发者_Go百科,(a+a*a)/2);
i--;
}
}
Now what i want to ask is how to make it shorter? Maybe some way using pointers instead of variables? Maybe this: (a+a*a)/2
can be done better?
Beware what you ask for...
#include <iostream>
int main()
{
int a;
for (int i = 10;
i-- && (std::cin >> a) && (std::cout << (a + a * a) / 2); )
;
}
(this also includes error checking, which you didn't bother with)
EDIT: Chris's comments below reveal this to be a terse-programming challenge (and not about legibility, robustness etc.). His teacher claims a 54 character implementation.
Have to wonder whether that include spaces and newlines?
The tightest implementation I've got so far is:
#include<iostream.h>
int main(){for(int i=10,a;i--;)cin>>a,cout<<(a+a*a)/2;}
This uses the deprecated header iostream.h
to remove the need to explicitly find cin
and cout
in std::
. It's still 74 characters (LF newlines on both lines).
As a thought experiment, let's assume we had a header "x" that declared functions int g()
(get an int from stdin) and void p(int)
(write an int to stdin). The implementation would then be...
#include<x>
int main(){for(int i=10,a;i--;)a=g(),p((a+a*a)/2);}
...which is still 64 characters.
Another technique commonly used to shorten code is preprocessor tricks, but the obvious one here - loop unrolling - doesn't look promising. It could look like...
#define X ...
int main(){X X X X X X X X X X}
...but if you compare for
loop code to the #define
-necessitated code...
for(int i=10,a;i--;)
#define X X X X X X X X X X X
...we're clearly going backwards.
Summarily, I simply can not imagine any approach shaving 10 characters off the <iostream.h>
version above. If he has a 54-character implementation, I think the requirements must have been miscommunicated in the question. If not, I do hope Chris will post it later :-).
One way you can shorten this is to use a for
loop instead of a while
loop. Try using
for (i = 10; i > 0; --i) {
Rather than your current while
statement. This eliminates the need for the i--;
line.
I'm not sure what you mean by making this code shorter "using pointers" though. Adding pointers won't help here.
Using this for
loop, your code would look like:
#include<stdio.h>
int main()
{
int i, a;
for (i = 10; i > 0; --i)
{
scanf("%d",&a);
printf("%d\n",(a+a*a)/2);
}
}
This removes one line. The only way of removing more lines would be to make this code less readable, or by changing your code style (which is completely unnecessary).
精彩评论