//5-7-1
//函数的可变参数
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h> //有很多宏
double add(int num, ...)
{
double last = 0.0;
va_list p; //创建一个char类型的指针
va_start(p, num); //读取有多少个参数,并把地址放在p中
for (int i = 0; i < num; i++)
{
double temp = va_arg(p, double); //按照double类型挨个读取参数
printf("\n%f", temp);
last += temp;
}
va_end(p); //读取结束
return last;
}
void main()
{
int x = 5; // 定义参数的个数
double result = 0.0;
result = add(x, 1.2, 2.3, 3.4, 4.5, 5.6);
printf("\n总和为:%f", result);
system("pause");
}
</pre><pre name="code" class="cpp">
</pre><pre name="code" class="cpp"><pre name="code" class="cpp">//5-7-2
//sprintf函数的应用
#define _CRT_SECURE_NO_WARNINGS //这里用VS2013关闭安全检查,不然就要把scanf编程scanf_s
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
void open(int num)
{
char str[100];
//sprintf 输出到字符串 , printf输出字符串到屏幕
sprintf(str, "for /l %%i in (1,1,%d) do start notepad", num);
system(str); //执行字符串指令,是一个变量
}
void main()
{
open(5);
system("pause");
}
</pre><pre name="code" class="cpp">//5-7-3
//函数可变字符串
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h> //有很多宏
#include <string.h>
#include <windows.h>
void go(int num, ...)
{
va_list p; //创建一个char类型的指针
va_start(p, num); //读取有多少个参数,并把地址放在p中
for (int i = 0; i < num; i++)
{
char str[50];
strcpy(str, va_arg(p, char*));//按照字符串的方式读取一个参数,拷贝到str,
system(str); //执行str
}
va_end(p); //读取结束
}
void main()
{
go(2, "notepad", "taskmgr"); //打开记事本和任务管理器
system("pause");
}