C 语言教程 在线

1549C 预处理器

回复楼上,不建议使用异或运算实现 swap,具体可参看链接:C 关于使用异或运算交换两数的值

1548C 预处理器

用#define宏定义将a,b交换,不使用中间变量,两种方法实现swap(x,y);

#include <stdio.h>
#define MAX(x,y) ((x>y)?(x):(y))
#define SWAP1(x,y) {x=x+y;y=x-y;x=x-y;}
#define SWAP2(x,y) {x=x^y;y=x^y;x=x^y;}

int main()
{
    int a,b;
    scanf("%d %d",&a,&b);
    printf("Max number is:%d\n",MAX(a,b));
    printf("交换前:x=%d,y=%d\n",a,b);
    SWAP1(a,b);
    printf("交换后:x=%d,y=%d\n",a,b);
    SWAP2(a,b);
    printf("再次交换后:x=%d,y=%d\n",a,b);
    return 0;
}

输出结果为:

2 4
Max number is:4
交换前:x=2,y=4
交换后:x=4,y=2
再次交换后:x=2,y=4

1547C 预处理器

使用#define含参时,参数括号很重要,如上例中省略括号会导致运算错误:

#include <stdio.h>

#define square(x) ((x) * (x))

#define square_1(x) (x * x)

int main(void)
{
   printf("square 5+4 is %d\n", square(5+4));  
   printf("square_1 5+4 is %d\n", square_1(5+4)); 
   return 0;
}

输出结果为:

square 5+4 is 81
square_1 5+4 is 29

原因:

square   等价于   (5+4)*(5+4)=81
square_1 等价于   5+4*5+4=29

1546C 文件读写

在 Visual Studio 2015 开发环境中运行下列代码, 会提示 fopen 函数不安全:

#include <stdio.h>
int main() {
    // 申明文件指针
    FILE *filePointer = NULL; 
    // 以追加模式打开文件 test.txt, 其中路径参数用正斜杠("/")
    filePointer = fopen("C:/Users/Administrator/Desktop/test.txt", "a+");
    // 在test.txt文件末尾追加写入
    fputs("The text was added to the file by executing these codes.", filepointer);
    // 关闭文件
    fclose(filepointer);
    return 0;
}

错误提示:

错误C4996'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

解决办法,在代码首行写上:

#define _CRT_SECURE_NO_WARNINGS

定义宏忽略警告, 即可忽略安全警告, 生成运行。

1545C 文件读写

fseek 可以移动文件指针到指定位置读,或插入写:

int fseek(FILE *stream, long offset, int whence);

fseek 设置当前读写点到 offset 处, whence 可以是 SEEK_SET,SEEK_CUR,SEEK_END 这些值决定是从文件头、当前点和文件尾计算偏移量 offset。

你可以定义一个文件指针 FILE *fp,当你打开一个文件时,文件指针指向开头,你要指到多少个字节,只要控制偏移量就好,例如, 相对当前位置往后移动一个字节:fseek(fp,1,SEEK_CUR); 中间的值就是偏移量。 如果你要往前移动一个字节,直接改为负值就可以:fseek(fp,-1,SEEK_CUR)

执行以下实例前,确保当前目录下 test.txt 文件已创建:

#include <stdio.h>

int main(){   
    FILE *fp = NULL;
    fp = fopen("test.txt", "r+");  // 确保 test.txt 文件已创建
    fprintf(fp, "This is testing for fprintf...\n");   
    fseek(fp, 10, SEEK_SET);
    if (fputc(65,fp) == EOF) {
        printf("fputc fail");   
    }   
    fclose(fp);
}

执行结束后,打开 test.txt 文件:

This is teAting for fprintf...

注意: 只有用 r+ 模式打开文件才能插入内容,ww+ 模式都会清空掉原来文件的内容再来写,aa+ 模式即总会在文件最尾添加内容,哪怕用 fseek() 移动了文件指针位置。