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

标签 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);

然后我在输入我的值后崩溃了。

最佳答案

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

首先,% 必须排在第一位。此外,如果您使用的是浮点值,d 不是正确的字符 - 它用于整数值。

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

最重要的是,您犯了一个小错误,没有为您的 scanf 调用之一使用指针:

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

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

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

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

因此,您在此程序中需要scanf 格式字符串只有"%d""%lf"(f 用于 float ,lf 用于 double )。

关于C - scanf 被跳过(即使是 "%d"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28101626/

相关文章:

c - 非数字输入导致死循环

string - 在 MATLAB 中高效使用 sscanf

closeir() 会导致现有列表的节点发生变化

c - 这个快速排序有什么问题吗?

c - 使用整数纹理坐标从一维纹理采样无符号整数

c - 结构指针段错误

c - sscanf 和正确的格式文件

c - 构建我自己的 scanf 函数

c - scanf() 将换行符保留在缓冲区中

c - 用普通 C 将文本文件读入数组