scanf function in objective-c, float and double - objective-c

I just a beginner in objective-C.
Below is a calculator of temperature.
I find a solution on the internet. The problem is the scanf.
At first, I set the f as a double, but program has problem.
So I change it to float.
May I ask what's going on on scanf function in objective-c?
Only can set character, int and float?
Another question is, what if I want to set a double, to use in another function which only accept double variable?
Thanks
import
int main(int argc, const char * argv[])
{
#autoreleasepool {
double c;
float f;
NSLog(#"Please enter F temp");
scanf("%f", &f);
c = (f-32) / 1.8;
//c = 1.3E-3;
// insert code here...
NSLog(#"The C temp is %.3f", c);
}
return 0;
}

Use %f for float and %lf for double. However be sure to check the return value from scanf() (or sscanf()) to ensure it parsed the correct number of values:
double d;
printf("Entry thy number mortal: ");
if (scanf("%lf", &d)) == 1) {
printf("Oh that's nice, you entered %f\n", d);
}

Related

How to use scanf in a Swift environment

I am practicing Objective C to get a better understanding of C and was using the newest Xcode, but using the terminal to write simple programs. In the the program below is can't seem to get the scanf function to work. Is there a different function that I can use to input data into the terminal to check the rest of syntax and coding?
#import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
int n, number, triangularNumber;
NSLog (#"What triangular number do you want?");
scanf ("%i", &number);
triangularNumber = 0;
for ( n = 1; n <= number; ++n )
triangularNumber += n;
NSLog (#"Triangular number %i is %i\n", number, triangularNumber);
return 0;
}
You can't have a space in between the scanf and (). The scanf function should turn purple when done correctly. Just take out the space and you should be fine.
You can try this (this is Swift, Objective C is the same):
let handle = NSFileHandle.fileHandleWithStandardInput()
let input = NSString(data: handle.availableData, encoding: NSUTF8StringEncoding)

How to express an imaginary number in method argument in Objective-C

"nan" and "nani" is being displayed in my output. I have discovered that this stands for "not a number", but I am not able to see where I am going wrong, and whether my problem lies with my lack of understanding of Objective-C, or imaginary numbers, or something else.
Any help or pointers would be much appreciated!
Thanks.
#import <Foundation/Foundation.h>
#interface Complex: NSNumber
-(void) setReal: (double) a;
-(void) setImaginary: (double) b;
-(void) print; // display as a + bi
-(double) real;
-(double) imaginary;
#end
#implementation Complex
{
double real;
double imaginary;
}
-(void) setReal: (double) a
{
real = a;
}
-(void) setImaginary: (double) b
{
imaginary = b;
}
-(void) print
{
NSLog (#"%f x %fi = %f", real, imaginary, real * imaginary);
}
-(double) real
{
return real;
}
-(double) imaginary
{
return imaginary;
}
#end
int main (int argc, const char * argv[])
{
#autoreleasepool {
Complex *complex1 = [[Complex alloc] init];
// Set real and imaginary values for first complex sum:
[complex1 setReal: 2];
[complex1 setImaginary: 3 * (sqrt(-1))];
// Display first complex number sum with print method:
NSLog (#"When a = 2 and b = 3, the following equation a x bi =");
[complex1 print];
//Display first complex number sum with getter method:
NSLog (#"When a = 2 and b = 3, the following equation
a x bi = %f x %fi = %fi", [complex1 real], [complex1 imaginary],
[complex1 real] * [complex1 imaginary]);
}
return 0;
}
Your NaNs come from sqrt(-1).
Do you want to implement your own complex types? C99 adds them, so unless you're using an ancient Objective-C compiler you'll be able to do something like this:
#include <complex.h>
double complex c = 3 * 2 I;
double r = creal(c);
double i = cimag(c);
There's some useful documentation and examples in the GNU libc manual: Complex Numbers.
The main problem is here:
[complex1 setImaginary: 3 * (sqrt(-1))];
The result of sqrt(-1) is NaN, sqrt() does not return "complex" numbers in any sense.
To set the imaginary part of your Complex object, you just set
[complex1 setImaginary: 3];
(setImaginary: expects a double argument, which makes sense because the imaginary part of a complex number is a real number.)
Remark: I have no idea what you want to achieve with your print method, but it does not
print a + bi as stated at the top of your program.

Scanf countdown

I am making a scanf countdown via objective-C, so the program will count down from what ever number you input. However, there's an annoying semantic error in the code saying:Data argument not used by format string. Also the program doesn't countdown, it just displays the output as zero once I input a number.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
int x,number;
NSLog(#"please enter a number:");
scanf("i", &number);
for (x = number; x>=0; x--)
NSLog(#"%i",x);
}
return 0;
}
You need to pass %i, not i in the format string of scanf.
When you pass i, the format string has zero format specifiers, leading to the semantic analyzer to produce a warning. That's also the reason why nothing gets entered into your number variable, so the countdown does not happen either.

using if statements with a string of letters and user input

Helllo I am still new to programing and had a question about using if statements while using user input with the research I have conducted i can't seem to find what I am doing wrong?
Below is my posted simple multiplication calculator.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
int a ;
int b ;
int c ;
printf("\n");
printf("\n");
printf("Welcome to calculator");
printf("\n");
printf("\n");
printf("what would you like to choose for first value?");
scanf("%d", &a);
printf("\n");
printf("What would you like to input for the second value?");
scanf("%d", &b);
c = a * b;
printf("\n");
printf("\n");
printf(" Here is your product");
printf("\n");
NSLog(#"a * b =%i", c);
char userinput ;
char yesvari = "yes" ;
char novari = "no";
printf("\n");
printf("\n");
printf("Would you like to do another calculation?");
scanf("%i", &userinput);
if (userinput == yesvari) {
NSLog(#" okay cool");
}
if (userinput == novari) {
NSLog(#"okay bye");
}
return 0;
}
You are scanning the character incorrectly with %i and you need to compare them using strcmp. If you are looking for a string from the user you need to use %s and you need a character buffer large enough to hold the input.
Try this
//Make sure userinput is large enough for 3 characters and null terminator
char userinput[4];
//%3s limits the string to 3 characters
scanf("%3s", userinput);
//Lower case the characteres
for(int i = 0; i < 3; i++)
userinput[i] = tolower(userinput[i]);
//compare against a lower case constant yes
if(strcmp("yes", userinput) == 0)
{
//Logic to repeat
printf("yes!\n");
}
else
{
//Lets just assume they meant no
printf("bye!\n");
}
I think you are reading a char using the wrong format %i: scanf("%i", &userinput);
And I think it is a better to use #NSString instead of simple char (I am not even sure what will happen in ObjC if you write char a = "asd", since you are giving a char a char[] value) . In that case, since strings are pointers, you cannot use == to compare them. You could use isEqualToString or isEqualTo instead. If you are interested in the difference between the two, look at this post would help.
In C, you can't compare strings using ==, so you would have to use a function like strcmp(), like this:
if ( !strcmp(userinput, yesvari) ) {
//etc.
}
The bang (!) is used because strcmp() actually returns 0 when the two strings match. Welcome to the wonderful world of C!

obtaining objective c nsstring from c char[]

code below.
i'm tryind to obtain string answers like "a1", "c4"
this is what i'm having instead of "a1": "adresse finale: \340}00\214"
with this prinf:
printf("\nadresse finale: %s",[self convertCGPointToSquareAdress:self.frame.origin]);
the method is:
-(NSString *) convertCGPointToSquareAdress:(CGPoint ) point{
int x= point.x /PIECE_WIDTH;
int y=point.y/PIECE_WIDTH;
char lettreChiffre[2];
//char chiffre;
NSString *squareAdress;
//ascii a=97 , b=98... h=105
for (int i=97; i<105; i++) {
for (int j=8; j>0; j--) {
if(i-97==x && j-1==y ){
NSLog(#"enterrrrrrrrrred if convertCGPointToSquareAdress");
lettreChiffre[0]=i;
lettreChiffre[1]=(char) j;
printf(" lettreChiffre: %s ", lettreChiffre);
NSString *squareAdress=[NSString stringWithFormat:#"%s", lettreChiffre];
break;
}
}
}
return squareAdress;
}
can you please help me?
thanks in advance.
There are three problems I can see with your code:
1.
When you do
lettreChiffre[1]=(char) j;
remember j is a number between 1 and 8, so you're getting the ASCII character whose value is j, not the character 1...8. You should use
lettreChiffre[1]= '0' + j;
2.
lettreChiffre is a char array of length 2, which means there's no room for the terminal null character. This may work, but may give you gibberish. You should instead declare
char lettreChiffre[3];
lettreChiffre[2] = '\0';
3.
You're trying to use printf to print an NSString, which it can't do. Either use
NSLog(#"adresse finale: %#", mynsstring)
or convert the NSString back to a C-string:
printf("adresse finale: %s", [mynsstring UTF8String]);
Also, as noted by #dreamlax, you don't really need the loop. I assumed you were doing something else and ran into this trouble, so we're not really seeing the full code. But, if this is really the entirety of your code, then you can simply remove the loop as #dreamlax suggested.
What is the purpose of the loop? You have a loop that essentially brute forces a matrix to calculate the “square address”. Your method will also return an uninitialized pointer if x is greater than 8.
Your entire method could be made much simpler.
- (NSString *) convertCGPointToSquareAdress:(CGRect) point
{
unsigned int x = point.x / PIECE_WIDTH;
unsigned int y = point.y / PIECE_WIDTH;
// Do some range checking to ensure x and y are valid.
char lettreChiffre[3];
lettreChiffre[0] = 'a' + x;
lettreChiffre[1] = '1' + y;
lettreChiffre[2] = '\0';
return [NSString stringWithCString:letterChiffre encoding:NSASCIIStringEncoding];
}