首页 > 解决方案 > C程序运行时冻结

问题描述

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    int x1, x2, x3, 
        y1, y2, y3, 
        ystr1, ystr2, ystr3,  
        xstr1, xstr2, xstr3, 
        sstr1, sstr2, sstr3;

    printf("Insert.");
    scanf("%d%d%d%d%d%d", x1, y1, x2, y2, x3, y3);
    ystr1 = y2 - y1;
    xstr1 = x2 - x1;
    sstr1 = sqrt(pow(xstr1, 2) + pow(ystr1, 2));
    ystr2 = y3 - y2;
    xstr2 = x3 - x2;
    sstr2 = sqrt(pow(xstr2, 2) + pow(ystr2, 2));
    ystr3 = y3 - y1;
    xstr3 = x3 - x1;
    sstr3 = sqrt(pow(xstr1, 2) + pow(ystr1, 2));
    printf("Print %d, %d, %d", sstr1, sstr2, sstr3);
    return 0;
}

由于某种原因,每次我输入一个数字时,此代码都会冻结。我真的不知道这可能是什么原因造成的。是不是整数太多了?

标签: cdev-c++

解决方案


scanf函数需要指针作为参数,以便它可以修改您正在读入的变量。请记住,C 中的所有参数都是按值传递的。如果我们想用函数修改某些东西,我们需要传递它在内存中的地址(一个指针)。

即使没有启用显式警告,您的代码也会生成警告,这一点很明显。

test.c: In function ‘main’:
test.c:14:13: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
     scanf("%d%d%d%d%d%d", x1, y1, x2, y2, x3, y3);
            ~^
test.c:14:15: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘int’ [-Wformat=]
     scanf("%d%d%d%d%d%d", x1, y1, x2, y2, x3, y3);
              ~^
test.c:14:17: warning: format ‘%d’ expects argument of type ‘int *’, but argument 4 has type ‘int’ [-Wformat=]
     scanf("%d%d%d%d%d%d", x1, y1, x2, y2, x3, y3);
                ~^
test.c:14:19: warning: format ‘%d’ expects argument of type ‘int *’, but argument 5 has type ‘int’ [-Wformat=]
     scanf("%d%d%d%d%d%d", x1, y1, x2, y2, x3, y3);
                  ~^
test.c:14:21: warning: format ‘%d’ expects argument of type ‘int *’, but argument 6 has type ‘int’ [-Wformat=]
     scanf("%d%d%d%d%d%d", x1, y1, x2, y2, x3, y3);
                    ~^
test.c:14:23: warning: format ‘%d’ expects argument of type ‘int *’, but argument 7 has type ‘int’ [-Wformat=]
     scanf("%d%d%d%d%d%d", x1, y1, x2, y2, x3, y3);

所以而不是:

scanf("%d%d%d%d%d%d", x1, y1, x2, y2, x3, y3);

你想写:

scanf("%d%d%d%d%d%d", &x1, &y1, &x2, &y2, &x3, &y3);

运算符返回变量的&地址。

同样重要的是要注意scanf返回一个int值。该值表示读取的值的数量。您可能应该检查scanf("%d%d%d%d%d%d", &x1, &y1, &x2, &y2, &x3, &y3);返回6.

if (scanf("%d%d%d%d%d%d", &x1, &y1, &x2, &y2, &x3, &y3) == 6) {
   ...
}

您可能希望做的另一件事是为变量设置初始值。如果scanf失败,您仍然拥有该初始值。


推荐阅读