菜C替抄代码220613

今天时间太晚了根本没时间仔细看解决bug了

#include <stdio.h>
struct worker
{
	char num[10];
	char name[10];
	float salary;
};

int main()
{

	struct worker w[100], * p = w;
	int i, n=0;
	float sum = 0;
	printf("Please input the number of workers:");
	scanf("%d", &n);
	for (i = 0; i < n; i++)
	{
		printf("Please input %th workers information(workernumber:  name:  salary:)\n", i + 1);
		scanf("%s%s%f", p->num, p->name, p->salary);
		sum += p->salary;
		p++;
	}
	printf("The average salary is %.2f\n", sum / n);
	printf("The information of whose salary low than 2000.0:\n");
	p = w;
	printf("The number of work\t name\tsalary\n");
	for (i = 0; i < n; i++)
	{
		if (p->salary < 2000.0)
			printf("%s\t%s\t%.2f\n", p->num, p->name, p->salary);
		p++;
	}
	while (1);
	return 0;
}
c++·c
162 views
Comments
登录后评论
Sign In
·

第二个printf函数那里的%th改为%dth(猜测的)

第二个scanfp->salary应该传地址,否则读不进值,然后还产生各种问题

我测试时未传地址在VS2022会给出警告,内容如下:(忽略scanf返回值未使用警告)

C6066 传递了非指针作为 _Param_(4),而对“scanf”的调用需要指针参数,实际类型: “float”
C4477 “scanf”: 格式字符串“%f”需要类型“float *”的参数,但可变参数 3 拥有了类型“double”

仔细看就能发现问题

VSCode中使用clangd扩展给出警告,如下:

Format specifies type 'float *' but the argument has type 'double'clang(-Wformat)

Shell中使用gcc编译打开所有警告的命令如下:

gcc -o 2.exe 2.c -Wall

警告如下:

2.c: In function 'main':
2.c:20:29: warning: format '%f' expects argument of type 'float *', but argument 4 has type 'double' [-Wformat=]
   20 |                 scanf("%s%s%f", p->num, p->name, p->salary);
      |                            ~^                    ~~~~~~~~~
      |                             |                     |
      |                             float *               double
2.c:20:29: warning: format '%f' expects argument of type 'float *', but argument 4 has type 'double' [-Wformat=]
   20 |                 scanf("%s%s%f", p->num, p->name, p->salary);
      |                            ~^                    ~~~~~~~~~
      |                             |                     |
      |                             float *               double

所以不能简单忽视各类警告

·

哦对了,你这个运行时警告看起来像VC++6的,应该放弃使用,VC++6的问题很多,VS2022相当好用,scanf警告加宏#define _CRT_SECURE_NO_WARNINGS就可以解决