在第一个循环之后,迭代会忽略“员工姓名#:”并跳转到“员工的时薪:”和“工作时间:”进行循环的其余部分,直到完成。当我在“For Loop”中添加“Float”数组后,问题就开始了。
这是我得到的输出:
员工 1 的姓名:Alex 员工时薪:9.00 工作时间:8
员工2姓名:员工时薪:9.50 工作时间:8
员工3姓名:员工时薪:10.00 工作时间:8
等等...
#include <stdio.h>
int main()
{ int i;
char empNames[5][32];
float empRates[5][10];
float empHours[5][10];
for (i = 0; i < 5; i++)
{
printf("Name of employee %d: ", i+1);
gets(empNames[i]);
printf("Employee's hourly rate: ");
scanf_s("%f", &empRates);//squiggly green line
printf("Hours Worked: ");
scanf_s("%f", &empHours);//squiggly green line
}
}
错误: - 警告 C4477 'scanf_s':格式字符串 '%f' 需要类型为 'float ' 的参数,但可变参数 1 的类型为 'float ()[5][10]'。
-警告 C6272 当调用“scanf_s”需要 float 时,非 float 作为参数“2”传递 实际类型:“float [5][10]”。
-警告 C4013“获取”未定义;假设 extern 返回 int。
最佳答案
首先:使用 gets 是危险的,您可以使用 fgets 来代替检查此以获取更多信息:Why is the gets function so dangerous that it should not be used?
第二:empRate[5][10]是一个二维数组(矩阵),您只需要一个一维数组来保存 float ,每个 float 可以容纳在empRate[i]中(对于empHours也是如此)
#include <stdio.h>
int main()
{
int i;
char empNames[5][32];
float empRates[5];
float empHours[5];
for (i = 0; i < 5; i++)
{
printf("Name of employee %d: ", i+1);
scanf("%32[^\n]s",empNames[i]);
printf("Employee's hourly rate: ");
scanf("%f", &empRates[i]);
printf("Hours Worked: ");
scanf("%f", &empHours[i]);
fgetc(stdin); // clear the buffer from the new line character
}
}
关于c - 如何在 For 循环中使用多个 Char 数组和 Float 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57023465/