C - simple math argument not working?

瘦欲@ 提交于 2019-12-13 02:54:41

问题


I am just trying to calculate an amount for 10 years, using a relatively simple formula. I can input all of my variables, but I suspect I'm doing something wrong with the amount.

#include <stdio.h>
#include <math.h>

int main(){
    double amount; /* amount on deposit */
    double principal; /* what's the principal */
    double rate; /* annual interest rate */
    int year; /* year placeholder and no. of total years */
    int yearNo;

    printf("What is the principal? ");
    scanf("%d", &principal);
    printf("What is the rate (in decimal)? ");
    scanf("%lf", &rate);
    printf("How many years? ");
    scanf("%d", &yearNo);

    printf("%4s%21s\n", "Year", "Amount on deposit");

    /* calculate the amount on deposit for each of ten years */
    for (year = 1; year <= yearNo; year++ ){
        amount = principal * pow(1.0 + rate, year);
        printf("%4d%21.2f\n", year, amount);
    }
    return 0;
}

I'm new to C, but am following an example in a book. The book "hard codes" the numbers, where I'm trying to learn how to use the input from a user to calculate the data.

Am I right in thinking it's either my amount or how I refer to it with the %f at the end?

Thanks for any ideas :)


回答1:


With the scanf() family of functions, %d is for int but %lf is for double.

The first thing to do is to make sure you've got warnings turned on for your compiler. Some compilers (GCC, Clang) report format errors like that.

The next thing to do is print the values you read. When you see garbage coming out for the values you just read, you know there's a problem.

And after that, you check that the conversions succeeded:

if (scanf("%lf", &principal) != 1)
    …oops! input error or EOF…


来源:https://stackoverflow.com/questions/28102910/c-simple-math-argument-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!