简体   繁体   中英

How do I fix error "use of undeclared identifier n" in C?

I'm sure there are probably tons of syntax/other errors, but I'm trying to figure out the two that it's picking up on. I'm very new to this so I don't really know how to fix undeclared identifiers. Note that #include <cs50.h> is just CS50's library.

#include <cs50.h>
#include <stdio.h>

int main (void)
{ 
   int add, fee, disc;
   printf("For rate with tax and Security Deposit, type y. For 10 percent off, type n:"); 
   string name = GetString();
   if (name == y)
   { 
     printf("PreTax Amount: ");
     scanf("%d", &fee);
     printf("Okay. I will add the 10 percent tax to %d.\n ", fee);

     add        = (1.1 * fee);

     printf("Plus Tax Amount = %d\n", add);
     printf("Security Deposit = 1000 dollars\n");
     printf("Total = (%d + 1000)", add); 
   }  
   else if (name == n)
   {
     printf("PreTax Amount: ");
     scanf("%d%d", &fee, &disc);
     printf("Okay. I will minus the 10 percent discount to %d and then add tax.\n ", fee);

     add        = (0.9 * fee);
     disc       = (add * 1.1);

     printf("Minus Discount Amount plus tax = %d\n", disc);
     printf("Security Deposit = 1000 dollars\n");
     printf("Total = (%d + 1000)", disc);
   }

   return 0;
}

errors:

ContractualHelper.c:10:17: error: use of undeclared identifier 'y'
if (name == y)
            ^
ContractualHelper.c:22:22: error: use of undeclared identifier 'n'
else if (name == n)
                 ^
2 errors generated.

y and n are undeclared because they do not have definitions.

int y; is a declaration, which would get rid of that error.

However, your code

if (name == y)

is comparing a variable name to a variable y , and I think what you want to do is see if name contains the string y .

How to do that comparison is another issue.

Since you want just to compare with either 'Y' or 'N' I suggest you use char instead of string . so : char name;

scanf("%c", &name);

than when comparing use :

if (name == 'Y') ...

ADD

you also should consider wrong inputs from user so add another else like :

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

main()
{
   char name;
   scanf("%c", &name);

   if (name == 'y') 
    printf("Yes");

   else if (name == 'n')
    printf("No");

   else 
        printf("wrong input");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM