#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
float gross=0,otp=0,ot=0,pay=0;
int IC,hours=0;
char name[50];
char category;
char rep = 'y';
while(rep == 'y')
{
printf("\n\n Name : ");
gets(name);
printf("\n NRIC : ");
scanf ("%d",&IC);
printf("\n Category : ");
scanf ("%s",&category);
printf("\n Total Hours : ");
scanf("%d",&hours);
if (category = 'A1') //Line 25
{
if (hours < 44)
{
printf("\n INVALID INPUT\n");
}
else if (hours >= 44 && hours <= 60)
{
gross= 44*5;
ot= (hours-44)*(1/2*5);
pay=gross+ot;
printf("\n Syarikat Smart Store Hypermarket Sdn. Bhd. ");
printf("\n =============================================================="); //Line 39
printf("\n Name: %s", name);
printf("\n NRIC: %d", IC);
printf("\n Category: %s", category);
printf("\n Total Hours: %d", hours);
printf("\n Gross Pay: RM %.2f", gross);
printf("\n Overtime Pay: RM %.2f", ot);
printf("\n Net Pay: RM %.2f", pay);
}
else
{
printf("\n\n INPUT NOT VALID");
除了第 25 行声明多字符字符常量警告之外,我在代码中没有看到任何错误,但程序一直运行到第 39 行并崩溃。知道为什么或者我的代码中有任何错误导致这个问题吗?
最佳答案
至少存在两个问题,其中之一已被编译器指出: 'A1' 不是单个字符,而是用单引号 (') 括起来的字符。您需要双引号。
此外,可能更重要的是:
您实际上并没有在第 25 行中执行比较,您正在更改category
( = vs == ) 的值,因此这意味着如果您的输入与A1
无关,因此其他事情可能是错误的或不适合输入这个特定的if
。
编辑:如果您确实使用C
,那么您应该使用差异函数来比较您的字符串,如 this page 中所示。指向 this thread
所以你至少需要添加
#include <string.h>
然后将您的 if
更改为类似
if ( strncmp(category,"A1",2) == 0 ) //Line 25
我假设您将 category
变量的定义更改为例如char[50]
就像您的 name
一样,并且您的类别始终只有两个字母。
我的编译器还发出警告
warning: ‘char* gets(char*)’ is deprecated
所以你可能也应该考虑摆脱这种情况。
关于c++ - 当我在 Dev C++ 中编译和运行时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32205953/