简体   繁体   中英

random value is being outputted when I am printing a character

My Code is Below, I am new to coding in C but fluent in Java:

#include<stdio.h>

int main(){

   int number;
   int firstInitial; 
   int lastInitial; 

   
   printf("\n\nEnter your first initial: ");
   scanf("\n\n%c", &firstInitial);

   printf("\nFirst Initial: %c", firstInitial);
   (int)firstInitial;
   printf("\nFirst Initial Decimal Value: %d", firstInitial);
   
   //Second Initial 
   
   printf("\n\nEnter your Last Initial: ");
   scanf("\n\n%c", &lastInitial);
   printf("\nLast Initial: %c", lastInitial);
   (int)lastInitial;
   printf("\nLast Initial Decimal Value: %d", lastInitial);
   
  
return 0;

} 

The problem in my output is that after I cast the character into an int, it outputs a random 7 digit number. For example, for first initial I've inputted "a" and received "4194401" instead of 97. The program is supposed to take in a character, and print both the character and it's character decimal value in the ASCII chart.

I have changed the datatype of firstInitial and lastInitial to char , since you are asking for a character. Also, the (int)firstInitial and (int)lastInitial statements do nothing - the code works fine with or without them.

#include<stdio.h>

int main(){

       int number;
       char firstInitial; 
       char lastInitial; 

   
       printf("\n\nEnter your first initial: ");
       scanf("\n\n%c", &firstInitial);

       printf("\nFirst Initial: %c", firstInitial);
   
       printf("\nFirst Initial Decimal Value: %d", firstInitial);
   
   //Second Initial 
   
       printf("\n\nEnter your Last Initial: ");
       scanf("\n\n%c", &lastInitial);
       printf("\nLast Initial: %c", lastInitial);
   
       printf("\nLast Initial Decimal Value: %d", lastInitial);
   
  
       return 0;

}

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