在我使用 quit 命令之前 C 不会运行

标签 c scanf

各位程序员。我对这个领域很陌生,这就是为什么我可能会遇到问题。

我被告知要编写一个程序来计算圆的面积和周长。一种情况,将输出显示到小数点后 5 位。输出应如下所示。

圆的半径是________。

圆的直径是_______。

圆的面积是__________。

周长是____________。

这是我为这个问题编写的代码。

#include<stdio.h>
    int main()
    {
        float r, area, circ, diam, pi = 3.14159;

        printf("Enter the radius please");
        scanf("%f\n", &r);

        printf("The radius of the circle is %0.5f\n", r);

        diam = 2 * r;
        printf("The diameter of the circle is %0.5f\n", diam);

        area = pi * r * r;
        printf("The area of the circle is %0.5f\n", area);

        circ = 2 * pi * r;
        printf("The circumference of the circle is %0.5f\n", circ);

        return 0;
    }

代码运行并在终端中显示这个

Enter the radius please4

我将 4 作为测试样本。这是程序刚刚停止工作的时候。我键入 q 并按回车键。这是其余输出显示的时候。

The radius of the circle is 4.00000
The diameter of the circle is 8.00000
The area of the circle is 50.26544
The circumference of the circle is 25.13272

最佳答案

问题出在您的scanf 格式字符串中:

scanf("%f\n", &r);

通过将 \n 放入格式字符串中,它会消耗您输入的任何换行符并等待不是换行符的字符。

从格式说明符中删除 \n 它将按预期工作:

scanf("%f", &r);

关于在我使用 quit 命令之前 C 不会运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46146133/

相关文章:

c - 过滤后的 scanf 导致无限循环

C 以用户输入结束循环

c - 让 fscanf 存储在 C 中的结构中

c++ - 不理解 sscanf_s 行为

c - 为什么 scanf() 需要 "%lf"来表示 double ,而 printf() 只需 "%f"就可以了?

c - 当 PIC32 上使能中断时,不等于运算符不工作

c - 这个现代编程面试挑战的解决方案不可靠吗?

C编程: Read file and search in a second file based on the data found

c - 我的 for 循环是否有问题导致它在屏幕上显示不正确的星号?

c - 在数组中查找总和最接近或等于给定数字的 5 个元素