定义一个函数,该函数将输出double
类型的值数组。double
数组作为参数与数组中的元素数一起传递。该函数的原型如下:
void show(double array[], int array_size, int field_width);
这些值应该输出五行到一行,每行在小数点后面有两个位置。
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_COUNT 100
void show(double array[], size_t array_size, unsigned int field_width);
int main(void)
{
double array[MAX_COUNT] = { 0.0 };
size_t count = 0;
for (double x = 1.5; x < 4.6; x += 0.3)
array[count++] = x;
unsigned int width = 12;
show(array, count, width);
printf_s("\n");
system("pause");
}
void show(double array[], size_t array_size, unsigned int field_width)
{
char format[10] = { '\0' }; // 保存格式字符串
unsigned int places = 2;
sprintf_s(format, sizeof(format), "%%%u.%ulf", field_width, places);
// 将值每五个输出一行
for (size_t j = 0; j < array_size; ++j)
{
if (j % 5 == 0)
printf_s("\n");
printf_s(format, array[j]);
}
}
执行上面示例代码,得到以下结果:
1.50 1.80 2.10 2.40 2.70
3.00 3.30 3.60 3.90 4.20
4.50