Using a for loop to print an interest compounding table
Hey, i'm new here and looking for some help with a program. I have to use a for loop to print an interest compounding table. So for example, when i type in 0.05 for the rate and 3 for the number of years, i get huge numbers like this... Shouldn't i be getting small #s for the balance, like 1.1, 1.2, etc?
Years Balance ------------- 1 10284435 2 2147483647 3 2147483647 Here's my code... #include <stdio.h> int main (void) { int i, rate, years, balance; printf("Type in integers rate and years, both <10.\n"); scanf("%f%d", &rate, &years); printf("Years Balance\n"); printf("-------------\n"); balance=1; for(i=1; i<=years; i++){ balance+=balance*(1+rate/100.0); printf("%d %d\n", i, balance); } return 0; } |
int's versus floats versus printf specs
Quote:
Take a look at scanf. Notice that the format string might not match the actual type you fed it. scanf has no way of knowing that the type you fed it doesn't actually match a float (probably not exactly true in some GLIBC's but I digress, but perhaps you don't have -Wall -pedantic turned on??? but you should). Do a "man printf" on your Linux box to get an idea of the printf specs such as "%d" and try to understand how %d matches up with which numeric types, int or floats. <hint> <hint> ;) bgoodr |
I think what bgoodr is trying to point out is that your use of scanf() is incorrect. You are telling scanf() to convert to a floating point format, but then store the converted value in an integer variable. You need to either change your scanf() format string to match the variable type (use "%d %d"), or probably better, use float or double type for your 'rate' and 'balance' variables.
--- rod.. |
Yep it is for a programming assignment in C...
Anyway, when i change to %d for everything and type in the rate and years, i get no output... And when i change the scanf function to %f for rate and %f for the balance output, it comes out as 0.000 for the first year, and then NaN for the other two years.:confused: |
Use floating point data types as appropriate for the values they represent. Pay attention to promotion and rounding rules for conversions between data types. Pay attention to format strings for both printing and scanning functions.
--- rod. |
All times are GMT -5. The time now is 08:34 PM. |