【问题标题】:C anomaly invalid outputC异常无效输出
【发布时间】:2021-10-08 20:49:26
【问题描述】:

我的代码需要使用标准输入的参数运行一些函数。第一个函数计算参数的阶乘,第二个函数计算长度和圆的平方,半径由参数表示。第三只需要 printf 它的论点。但是在我输入之后,我得到了非常奇怪的结果。我的 IDE 是 Xcode

输入:

5
1.3
8
8
fgd

预期输出:

120
Obvod: 8.168134 Obsah: 5.309287
88fgd

实际输出:

120
Obvod: 8.168134 Obsah: 5.309287
88
fg

上次输入有什么问题?非常感谢您的回答!整个代码如下:

#include <stdio.h>
#include <stdlib.h>
int factorial (int value)
{
    int fac = value;
    if (value == 0)
    {
        return 1;
    }
    else if (value < 0)
    {
        return 0;
    }
    for (int i = 1; i < value; i++)
    {
        fac *= value - i;
    }
    return fac;
}
void radius (float rad, float* lep, float* sqp)
{
    const float pi = 3.14159;
    if (rad < 0)
    {
        printf("Obvod: 0 Obsah: 0\n");
    }
    float lenght = 2 * pi * rad;
    float square = pi * (rad * rad);
    *lep = lenght;
    *sqp = square;
    printf("Obvod: %f Obsah: %f\n", lenght, square);
   
}
void read_array_data(int h, int w, char x1, char x2, char x3)
{
    printf("%i%i%c%c%c\n", h, w, x1, x2, x3);
    
}
int main()
{
    char c1;
    char c2;
    char c3;
    int f, height, width;
    float r;
    float radius_container, square_container;
    float* p1 = &radius_container;
    float* p2 = &square_container;
    scanf("%i", &f);
    scanf("%f", &r);
    scanf("%i", &height);
    scanf("%i", &width);
    scanf("%c%c%c", &c1, &c2, &c3);
    printf("%i\n", factorial(f));
    radius(r, p1, p2);
    read_array_data(height, width, c1, c2, c3);
}

【问题讨论】:

    标签: c xcode


    【解决方案1】:
    scanf(" %c%c%c", &c1, &c2, &c3);
    //    ^^^ insert space here
    

    当您从之前的 scanf 按 Enter 键时,stdin 中会留下一个换行符。该换行符被读入c1f 被读入c2,最后g 被读入c3。打印时,换行符打印到下一行,然后是fg。前导空格告诉scanf 跳过该前导空格。之后,fgd 字符将按您的预期读入c1, c2, c3

    Demonstration

    更多信息请见scanf("%c") call seems to be skipped

    【讨论】:

      猜你喜欢
      • 2021-03-25
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多