C - scanf被跳过(即使使用"%d")

时间:2015-01-23 01:26:43

标签: c scanf

我试图找出为什么我无法让它正常运行。我只想要用户输入四个,并在最后运行计算。

#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(" .2%d", &rate);
    printf("What is the principal? ");
    scanf(" %d", &principal);
    printf("How many years? ");
    scanf(" %d\n", 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;
}

它正确地询问了本金和利率,但随后跳过了关于委托人的问题并要求多年。然后它只是坐在那里等待“鬼”条目?

我一直在阅读scanf()在点击enter时添加了一些空格但是认为%d之前的空格会解决这个问题?

我还看到你可以在每个do { c=getchar(); } while ( c != '\n');之后添加scanf,但这似乎会导致程序崩溃(我也将int c = 0;添加到了开头)。

感谢您的帮助或想法!

修改

当我从:

更改错误的格式说明符时
scanf(" .2%d", &rate);

为:

scanf(" %d", &rate);

输入我的值后,我就崩溃了。

1 个答案:

答案 0 :(得分:5)

.2%d 不是有效的格式字符串。

首先,%必须先行。此外,如果您在浮点值之后,d不是正确的字符 - 它是积分值。

你应该使用%f之类的东西(你不需要宽度或精度修饰符)。

最重要的是,您在scanf个来电之一中没有使用指针时犯了一个小错误:

scanf(" %d\n", yearNo);

这可能会导致崩溃,应该改为:

scanf(" %d\n", &yearNo);

而且,作为最终建议,完全没必要在%d%f格式说明符族之前使用空格(或换行后的换行符)。扫描仪会自动跳过这两个空格。

因此,此程序中 所需的唯一两个scanf格式字符串为"%d""%lf"f用于浮点数,{ {1}}是双打的。)

相关问题