Thread: a bug in my mini program!

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    56

    a bug in my mini program!

    When I run my this program, after day 18 it gives me negative numbers. Where it should be positive. Can someone tell me why?

    I'm just preparing for my test.

    Code:
    #include <stdio.h></stdio.h>
    int main ()
    {
    int loop_counter = 0;
    int algea = 1000000;
    int sum = 0;
    while (loop_counter<150)
    {
        sum=sum*1.5+algea;
        loop_counter= loop_counter+1;
        printf ("Day %d\t Total algea %d\n",loop_counter, sum);
    }
    return 0;
    }

  2. #2
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    You're probably trying to store a value that's too big for an int to deal with. Try declaring sum as a double instead.

    You need to do this anyway, because multiplying by 1.5 is floating point arithmetic.
    Code:
    while(!asleep) {
       sheep++;
    }

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You are probably just exceeding the range of int. One way out would be to use a long long int instead. Another way out is to use a double, which may be more sensible since you are converting from double to int here (and truncating) anyway.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Sep 2011
    Posts
    56
    k, got it fixed, thank you so much.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mini chat
    By Annonymous in forum Networking/Device Communication
    Replies: 11
    Last Post: 05-25-2011, 09:40 PM
  2. Critique my mini-AES
    By Hughesz93 in forum C Programming
    Replies: 7
    Last Post: 05-04-2011, 03:49 PM
  3. Mini If
    By Milhas in forum C Programming
    Replies: 4
    Last Post: 03-27-2008, 04:04 PM
  4. New Mini Project
    By jverkoey in forum Game Programming
    Replies: 3
    Last Post: 05-12-2004, 11:00 PM
  5. mini-itx
    By whistlenm1 in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 06-18-2003, 03:58 PM