C: Operators - Atoi Does Not Rhyme with All-Gooey
(Page 2 of 4 )
We can also work with what is called mixed mode arithmetic, such as 12.9 + 2. In the below example, we are going to multiply a float by a character...I know...your head's gonna explode when you see it in action. So get some Windex and paper towels...
#include <stdio.h>
#include <stdlib.h>
int main()
{
float myIQ;
char yourIQ[4];
printf("Enter your IQ: ");
gets_s(yourIQ);
myIQ = atoi(yourIQ)*5.52;
printf("My IQ is %.1f... I laugh at your puny IQ!n",myIQ);
return(0);
}
This program does several things: first, it demonstrates how superior my intelligence quotient is to yours. Second, it creates two variables, one a float and the other a character. It then gets input from the user and stores it in the variable “yourIQ.” Next, it extracts the data from yourIQ, and since it is a character variable, it translates the value into an integer using the ATOI function. Then it multiplies this new integer by 5.52 and stores its value in the variable myIQ. Finally it prints out some text and appends the value of myIQ to the end of the sentence.
If the user had lied and typed that their IQ was 129, then the result would be:
Enter your IQ: 129
MY IQ is 712.1... I laugh at your puny IQ!
You will note two new functions here:
ATOI, which I already introduced you to, but just as a reminder, it translates a value into an integer.
Gets_s, which is similar to scanf_s, except gets_s() reads only text.
Next: Relational Operators >>
More BrainDump Articles
More By James Payne