[英]I don't know why but the 2nd for loop for printing the id's is not working properly and a sometimes if I give length 9 to 3rd employee program exits
[英]why the program is not printing the 2nd employee's name?
該程序告訴哪個員工的任期等於 3 年或超過 3 年。 那么為什么程序不打印第二名員工的姓名呢?
代碼
#include <stdio.h>
#include <string.h>
int main()
{
struct employee
{
char name[30]; //name of employee
int emp_code; // employee code
int date[10]; // year of joining
} e,e3;
struct employee e1 = {"Mr.ABCDEF", 123, 2002};
struct employee e2 = {"Mr.UVWXYZ", 456, 2004};
printf ("Enter current date DD MM YYYY: ");
scanf ("%d %d %d" , &e3.date, &e3.date ,&e.date);
if ((e.date - e1.date) >= 3)
printf("Employee Code: %d Name: %s\n", e1.emp_code , e1.name);
else if ((e.date - e2.date) >= 3)
printf("Employee Code: %d Name: %s\n", e2.emp_code , e2.name);
return 0; }
從 -'else if' 語句中刪除 'else'。
即兩個語句都應該在打印前測試長度。
if ((e.date - e1.date) >= 3)
printf("Employee Code: %d Name: %s\n", e1.emp_code , e1.name);
if ((e.date - e2.date) >= 3)
printf("Employee Code: %d Name: %s\n", e2.emp_code , e2.name);
盡管這些語句在邏輯和語法上都很好,但通過使用大括號使您的意圖明確,可提高可維護性......
if ((e.date - e1.date) >= 3)
{
printf("Employee Code: %d Name: %s\n", e1.emp_code , e1.name);
}
if ((e.date - e2.date) >= 3;
{
printf("Employee Code: %d Name: %s\n", e2.emp_code , e2.name);
}
打印第二個用戶位於 Else if 塊中。 因此,如果您打印第一個,則將跳過 else if。
把 else if 變成 if 應該會更好。
在scanf ("%d %d %d", &e3.date, &e3.date, &e.date);
您將三個整數讀入同一 memory 位置。 也許你的意思是scanf("%d %d %d", &e3.date[0], &e3.date[1], &e3.date[2]);
所以年月日 go 在日期數組的后續條目中。
在使用默認命令行 arguments 的 gcc 和 clang 下,編譯器警告這是錯誤的:
$ clang d.c
d.c:16:22: warning: format specifies type 'int *' but the argument has type 'int (*)[10]' [-Wformat]
scanf ("%d %d %d" , &e3.date, &e3.date ,&e.date);
~~ ^~~~~~~~
d.c:16:32: warning: format specifies type 'int *' but the argument has type 'int (*)[10]' [-Wformat]
scanf ("%d %d %d" , &e3.date, &e3.date ,&e.date);
~~ ^~~~~~~~
d.c:16:42: warning: format specifies type 'int *' but the argument has type 'int (*)[10]' [-Wformat]
scanf ("%d %d %d" , &e3.date, &e3.date ,&e.date);
~~ ^~~~~~~
因為您明確地向計算機僅打印其中一個,而是使用else
命令。
但是,您的代碼存在更大的問題,您應該收到多個警告但可能會被忽略:
您錯誤地使用了date
字段!
它被定義為整數數組,但您試圖將其用作單個 integer。
您的條件將始終正確,因為您真正比較的是兩個 arrays 的兩個 memory 地址,每個地址的大小均為sizeof(int) * 10
。
您真的應該從日期字段中刪除[10]
以使您的代碼按照您的預期工作!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.