Yet more C problems

Hi again, I’m writing a program that will given that you have $10,000 in the bank with 4% interest and you take out $1000 every month, how many months will you be able to do that?
my program:
#include <stdio.h>
unsigned long int total=10000;
unsigned long int total_two;
unsigned long int total_three;
//unsigned int total_fn(void);
int main()
int months=0;
printf("%d ",total);

printf("If you have 250,000 dollars in your account with 4%% interest,
printf("And you withdraw 1,000 dollars a month, you will be able to withdraw for %d months.
/unsigned int total_fn(void)

the problem is that when it runs, it prints wild random numbers and never gets to the printing the months because it is always greater than zero. the reason I have unsigned long int total_two&_three is because I thought that maybe the problem was total=total-1000 etc. but it still dosen’t work. What am I doing wrong? thanks

You should probably use floats instead of ints. And your numbers should have .0 on the end of them.

It’s funny how you answered yourself in your post. Of course unsigned long int is always greater than zero. That’s the whole point of it being unsigned :D.

When you reach the number total = 378, the next iteration goes like this
(378 - 1000) * 1.04 = 171798044

You get these results because of the internal binary representation of unsigned numbers. And yes it’s correct.

There are other problems with your algorithm - if total at the begining so big that 0.04 * total > 1000, the cycle will never end.

The number of months will sometimes be one larger that the number of moths you are allowed to withdraw.

etc. :slight_smile:

Actually you don’t have to use cycling at all, it’s strictly mathematical problem, which can be solved with one line (I won’t tell though, google for it or )

#include &lt;stdio.h&gt;
long int total = 10000;
int main()
        int months=0;
        while(total &gt; 0)
                total = (total-1000) * 1.04;

                if (total &gt;= 0)
", months);

Thank you! it works now. Now onto a completely different project. I’m doing a trivia thing and I want something like:
then do whatever…;

but I don’t know how to compare strings. Any help would be appreciated. Thanks.

I must say I like your enthusiasm :).

In C can compare strings with strcmp. However strcmp returns 0 if the strings are equal and not zero when they differ (it’s not very important which numbers it returns when they aren’t equal).

So you must do

char *buf1 = “buf1”;
char *buf2 = “buf2”;

if (strcmp(buf1, buf2) == 0)
printf("not equal

What I would suggest, is to take one day and listen to this seminar.

It’s awesome introduction to C. They explain why some things work the way they work in C and give you a generally very good insight in coding practices.