gpt4 book ai didi

c - 结束此逻辑循环后如何打印多行

转载 作者:太空宇宙 更新时间:2023-11-04 03:20:05 26 4
gpt4 key购买 nike

又是我。 C位菜鸟。我正在完成一项任务,编写一个程序,提示用户输入信息,之后程序应该列出回输入的数据。我的代码只打印最后输入的记录信息。

例如,我为员工 #1“Rookie Coder”输入以下信息作为第一个员工姓名,并分别输入 25 和 40 作为小时工资和工作时间。然后,我为员工 #2“Slow Learner”输入以下信息作为第二个员工姓名,并分别输入 20 和 45 作为小时工资和工作时间。该程序仅打印与“Slow Learner”相关的信息。但我想打印出输入的两条记录的信息。

有人可以就我缺少什么来打印这两个记录提供指导吗?来自C菜鸟的感谢

// C Libraries Used

#include <stdio.h>
#include <math.h>
#include <string.h>

// Constant declerations

const float OTPAYFACTOR = 1.5;
FILE *userinputfile; //disk file (for input)

// Variable declerations
char deptname [21];
char firstname [10];
char lastname [10];
char fullname [21];
float hrsworked;
float hrwage;
int count;
char again;

// Function Prototypes


// M A I N F U N C T I O N

int main (void){
printf("Mountain Pacific Corporation\nDepartment Salary Program\n\n");
printf("Please enter the name of the department: ");
scanf("%s", &deptname);
count = 0; // Initialize this "counting" variable to zero to start
printf("\n");
count = 0; // Initialize this "counting" variable to zero to start
printf("\n");
do {

count++; // Increment the counting variable

printf("Enter employee #%d: ", count);
scanf("%s %s", &firstname, &lastname);
strcpy(fullname, firstname);
strcat(fullname, " ");
strcat(fullname, lastname);
printf("Enter the hourly wage of %s: ", fullname);
scanf("%f", &hrwage);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked);

printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");

} while (again != 'N' && again != 'n');

printf("End of processing.");

printf("%s, $%0.2f, %0.2f: \n", fullname, hrwage, hrsworked);

return 0;
}

最佳答案

在循环的每次迭代中,您只有一组变量。第一次通过循环存储的任何内容都将在第二次通过循环时被覆盖。因此,您只会存储最近输入的一组值。

您想声明每个将数据作为数组的变量,这样您就可以保存多个值。

char deptname [5][21];
char firstname [5][10];
char lastname [5][10];
char fullname [5][21];
float hrsworked[5];
float hrwage[5];

...

do {

printf("Enter employee #%d: ", count+1);
scanf("%s %s", &firstname[count], &lastname[count]);
strcpy(fullname[count], firstname[count]);
strcat(fullname[count], " ");
strcat(fullname[count], lastname[count]);
printf("Enter the hourly wage of %s: ", fullname[count]);
scanf("%f", &hrwage[count]);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked[count]);

printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");

count++; // Increment the counting variable

} while (again != 'N' && again != 'n');

然后你需要遍历数组来打印每个元素:

int i;
for (i=0; i<count; i++) {
printf("%s, $%0.2f, %0.2f: \n", fullname[i], hrwage[i], hrsworked[i]);
}

关于c - 结束此逻辑循环后如何打印多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47243584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com