我正在尝试开始我的新计划。该程序将询问一家公司的 n
名员工,然后是姓名
、薪水
和当月销售额
。输出将显示先前的信息加上佣金
、net salary
和每一项的total
。
为了更好地理解,这将是输出:
Name Salary Sale of the month Comission Net salary
Elena Gomez 2000.00 1000.00 35.00 2035.00
Elle Johns 4000.00 1345.00 60.53 4060.53
Stefan Cox 3200.00 4000.00 216.00 3416.00
Total 9200.00 6345.00 311.53 9511.53
我的问题是我的代码与之前的输出不一致。我目前正在使用 int
数组和一个 char
多维数组。这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define NUMBER_OF_STRING 6
#define MAX_STRING_SIZE 50
void print_array(const char arr[][MAX_STRING_SIZE]);
int main ()
{
int numemployees, cont=0;
float salary[10], salnet[5], sale[5], comission[5][1], ind=0, total[1][50];
char header[0], nom[5][40];
char arr[NUMBER_OF_STRING][MAX_STRING_SIZE] =
{ "Name",
"salary",
"Sale of the month",
"Comission",
"Net salary"
};
printf("Enter # of employees to consult: \n");
scanf("%d",&numemployees);
for(int i=0; i<=numemployees; i++)
{
printf("Enter employee's %d name : ",cont); // I'd like to show it from #1 not zero.
scanf("%s", nom[i]);
printf("Enter employee's %d salary : ",cont);
scanf("%f", &salary[i]);
printf("Enter sale of the month of the employee %d : ",cont);
scanf("%f", &sale[i]);
cont++;
system("cls");
}
print_array(arr); // function that shows the headers
for(int i=0; i<=numemployees; i++)
{
printf("%s %-25f %-25f\n",nom[i], salary[i], sale[i]);
}
return 0;
}
print_array
函数:
void print_array(const char arr[NUMBER_OF_STRING][MAX_STRING_SIZE])
{
for (int i = 0; i < NUMBER_OF_STRING; i++)
{
printf("%-16s ", arr[i]);
if (i == 5)
{
printf("%-16s \n", arr[i]);
}
}
}
我的输出显示如下:
Name salary Sale of the month Comission Net salary
pedro 60.000000 45.000000
我尝试将 printf
与 %-25f
一起使用,但没有解决问题。请检查是否有遗漏或其他想法以获得正确的输出。提前致谢。
最佳答案
首先:
for(int i=0; i<=numemployees; i++)
{
printf("%s %-25f %-25f\n",nom[i], salary[i], sale[i]);
}
您应该像这样指示所有列的宽度:
for(int i=0; i<=numemployees; i++)
{
printf("%25s %25f %25f\n",nom[i], salary[i], sale[i]);
}
如果您在字符数 x 之前加上“-”,您将使用 x(在您的情况下为 25)个字符来表示信息,但您将获得左对齐的文本。
关于c - 如何对齐阵列以使其彼此适合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58479390/