c - 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;
}
由于某种原因,每次我输入一个数字时,此代码都会冻结。我真的不知道这可能是什么原因造成的。是不是整数太多了?
解决方案
该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
失败,您仍然拥有该初始值。
推荐阅读
- dictionary - 字典数学 Python
- python - discord.py - 添加反应作为命令的一部分
- node.js - Nodejs 在对安全端点的 GET 调用中抛出 EPROTO 错误
- vb.net - 漂亮的清单删除了继续符 (_) -> 编译器中的错误 BC30201 [Visual Studio 2019]
- java - 限制和分组流
- windows - 使用 FILE_OPEN_BY_FILE_ID、NtCreateFIle、ObjectID 打开文件时访问被拒绝
- python-3.x - 使用 Zappa 将烧瓶应用程序转换为 aws lambda
- c# - 使用 C# 使用 HTML 请求不提供表数据来抓取网站
- python - Python FTP 检索打破了 FOR 循环。我用 try-catch 块修复了它。为什么它有效?
- python - Kivy app AttributeError:“int”对象没有属性“value”