C-简单的数学参数不起作用? [英] C - simple math argument not working?

查看:127
本文介绍了C-简单的数学参数不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想使用一个相对简单的公式来计算10年的金额.我可以输入所有变量,但是我怀疑amount做错了什么.

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;
}

我是C语言的新手,但我正在按照书中的示例进行操作.这本书对数字进行了硬编码",在这里我试图学习如何使用用户的输入来计算数据.

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.

我是否正确地认为这是我的amount还是结尾处带有%f的引用方式?

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

感谢任何想法:)

推荐答案

对于scanf()系列功能,%d用于int,而%lf用于double.

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

要做的第一件事是确保已为编译器打开警告.一些编译器(GCC,Clang)会报告类似的格式错误.

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…

这篇关于C-简单的数学参数不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆