C异常无效输出



我有代码需要运行一些函数从stdin参数。第一个函数计算参数的阶乘,第二个函数用参数给出的半径计算长度和圆的平方。第三只需要打印它的参数。但是在我输入之后,我得到了非常奇怪的结果。我的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: 0n");
}
float lenght = 2 * pi * rad;
float square = pi * (rad * rad);
*lep = lenght;
*sqp = square;
printf("Obvod: %f Obsah: %fn", lenght, square);

}
void read_array_data(int h, int w, char x1, char x2, char x3)
{
printf("%i%i%c%c%cn", 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("%in", factorial(f));
radius(r, p1, p2);
read_array_data(height, width, c1, c2, c3);
}
scanf(" %c%c%c", &c1, &c2, &c3);
//    ^^^ insert space here

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

示范请参阅scanf("%c")调用似乎被跳过以获取更多信息

最新更新