Why does not my program is not running?
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Aug 20 14:10:27 PDT 2015
On 8/20/15 4:31 PM, Unknow wrote:
> module main;
>
> import std.file;
> import std.conv;
>
> long factorial(long i){
> if (i == 0){
> return 1;
> }else{
> return(i * factorial(i-1));
> }
> }
Note, this is not going to work. At 21!, long will run out of bits.
From https://en.wikipedia.org/wiki/Factorial, 100! is
9.332621544×10^157, requiring 157 *decimal* digits, not to mention the
base-2 digits that would be required.
>
> void main(string[] args){
> real *e; e = new real; *e = 0; long *integer; integer = new long;
> *integer = 1;
There is no need for this, you are making pointers from everything, just
declare the variables:
real e = 0;
long integer = 1;
> for(; *integer <= 100; *integer++){
And here is why you crash. *integer++ means return the value currently
pointed at by integer, then increment the POINTER by one. This points at
some garbage memory (on my system, it happens to be zeroed, so it didn't
crash).
Not using pointers will help a lot in this code.
> *e = (*e) + (*integer / factorial(*integer));
The second portion of this calculation is INTEGER math, which means
except for 1 / 1, it's going to be 0. What you want is (with new style
that doesn't use pointers):
e = e + (real(integer) / factorial(integer));
The real(...) casts the result to a real before continuing.
> }
> if(exists("e") != 0)
> {
> std.file.write("e", to!string(*e));
Just want to confirm here, you are writing e only if it *already exists*?
> }else{
> //...
> }
> delete(e); delete(integer);
Without pointers, you would remove these. In addition, you do not need
to delete pointers even if you did use them -- D is garbage collected.
> }
-Steve
More information about the Digitalmars-d-learn
mailing list