|
|
宝子觉得“越学越混乱”的原因:
其实C语言最容易犯错的地方就是 scanf、指针、格式化输入输出。你的逻辑是正确的,只是一个小小的格式串错误导致输入读取失败。
代码有些需要提高的地方
1、scanf 的格式串写错了
你写的是:
但正确写法应该是:
你把 %d 错写成 &d 了,所以 scanf 根本无法正确读取输入,导致 a 和 b 的值不正确,这是最关键的错误。
2、compare 函数没有返回值,但声明为 int
你定义了:
- int compare(int *p1,int *p2)
- {
- int temp;
- temp=*p1;
- *p1=*p2;
- *p2=temp;
- }
复制代码
虽然你没有 return 值,但 main 里也没有使用返回值,所以功能上不影响运行结果,不过更规范的写法应该是:
- void compare(int *p1,int *p2)
复制代码
否则编译器可能会给出 warning。
程序完整修正版如下:
- #include <stdio.h>
- void compare(int *p1, int *p2);
- int main()
- {
- int a, b;
- int *point1, *point2;
- scanf("%d,%d", &a, &b);
- point1 = &a;
- point2 = &b;
- if(a < b)
- {
- compare(point1, point2);
- }
- printf("%d,%d\n", a, b);
- return 0;
- }
- void compare(int *p1, int *p2)
- {
- int temp;
- temp = *p1;
- *p1 = *p2;
- *p2 = temp;
- }
复制代码
|
|