what is wrong with my code?

B

BobR

This is my own C++ code for finding the sum of an arithmetics
sequence,

#include <iostream.h>
void main () {

That's not C++. This is C++ <G> :

#include <iostream>
int main(){
using std::cout;
using std::cin;
using std::endl;
while( true ){

int n(0), result(0); // now 'result' IS cleared every loop
cout<<"enter n"<<endl;
cin>>n;
if( (n==-999) || (n==0) ){
break;
} // if(n)

// - put 'result' here -
// int result(0); // now 'result' IS cleared every loop
for( int i(1); i <= n; ++i){
result+=i;
} // for(i)
cout<<"result is"<<result<<endl;
} // while()~

return 0; // self documentation :-}
 
T

terminator

Yes. I think this is in the FAQ.








sizeof gives the number of _bytes_ not bits but I get the idea.

You got me again . I am really sorry for the mistake.
My point was to have code that is equivalent to the OP's who used int.
The ?: will not prevent overflow but guarantees that it will not overflow
for smaller n than the OP's code.

Using short as input with a long result may prevent overflow from
happening but may also limit the input range (this is all platform
specific since there is no guarantee that sizeof(short) < sizeof(long))

no guarantee but intriduce a platform who does not fit into the rule
that sizeof(long)>= 2*sizeof(short).

in case this is not satisfactory, use masking for overflow prevention:

unsigned sum(unsigned n){
enum{mask=(~0)<<sizeof(unsigned)*4};
if(n & mask) retun 0;//one can throw instead of return
return (n*(n+1))>>1;
};

and __int64 or long long or int64_t is non-standard.

Sure.it was just for clarification.

regards,
FM.
 
T

terminator

How do you know it is the faster way? (I've actually worked on
a machine, the NSC 32000, where it wasn't.) This sort of coding
is really rather amateurish, and wouldn't be allowed in any
reasonable company.
You obviously don't know very many machines, then. There are
machines on which short is the same size as long.

we agree on this.
If the results won't fit, there's not much you can do. His
solution won't overflow if the results are representable. Yours
will overflow for intermediate values even when the correct
results are representable.

what does the term intermediat mean please?
What does the cast change?

And of course, this may overflow although the results will fit.

it should have been like this:

return (n*( (long)n + 1 ))>>1;

now n+1 wont be zero -only if long is bigger than short.this is what I
wanted. but mistakes always happen.

regards,
FM
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,280
Latest member
BGBBrock56

Latest Threads

Top