Simple Objective-C calculator program printing continuously - objective-c

I'm writing my first real objective C program and it's to make a very simple calculator like in the book Programming in Objective-C 2.0 by Stephen Kochan.
Anyway, whenever I run the program it just continually prints the same thing over and over again, not giving me the option to type anything else. The code is below, and if anyone could help I think the problem is somewhere between the while loop and the switch function. Thank you in advance!
#import <Foundation/Foundation.h>
#interface Calculator : NSObject {
double number, accumulator;
char operator;
}
-(void) add: (double) n;
-(void) subtract: (double) n;
-(void) multiply: (double) n;
-(void) divide: (double) n;
#end
#implementation Calculator
-(void) add: (double) n {
accumulator += n;
NSLog(#"%fl", accumulator);
}
-(void) subtract: (double) n {
accumulator -= n;
NSLog(#"%fl", accumulator);
}
-(void) multiply: (double) n {
accumulator *= n;
NSLog(#"%fl", accumulator);
}
-(void) divide: (double) n {
if (n == 0)
NSLog(#"Error! You can't divide by 0!");
else
accumulator /= n;
NSLog(#"%fl", accumulator);
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
double number, accumulator;
char operator;
Calculator *myCalc = [[Calculator alloc] init];
NSLog(#"Begin calculations by typing a number then S");
scanf("%lf, %c", &accumulator, &operator);
while (operator != 'E') {
NSLog(#"%lf", accumulator);
NSLog(#"What would you like to do next?");
scanf("%lf, %c", &number, &operator);
switch (operator) {
case '+':
[myCalc add: number];
break;
case '-':
[myCalc subtract: number];
break;
case '*':
[myCalc multiply: number];
break;
case '/':
[myCalc divide: number];
break;
default:
break;
}
}
}
return 0;
}

scanf is generally a bad function to use. It's generally better to read an input line into a string and then use sscanf (or some other parser) on the string.
However, the fix in this case is simple. scanf returns the number of input items successfully assigned. You expect two. If there's an error, or end-of-file is reached, it will return less than two. Thus:
int rc = scanf("%lf, %c", &number, &operator);
if (rc < 2) {
break;
}

In short: don't use scanf(). It doesn't work how you think it does.
I'm already tried explaining what's wrong, but basically it doesn't like newlines and stuff and it's pedantic. Search SO for similar questions. The easy solution is to replace scanf() with something actually useful, such as
char buf[0x100];
char *end;
fgets(buf, sizeof buf, stdin);
accumulator = strtod(buf, &end);
while (isspace(*end))
end++;
operator = *end;
Also, your calculator logic is flawed. The myCalc object doesn't share the identically named accumulator variable with the main() function. Your program basically doesn't take into account the first number entered. Also, I don't see what purpose the "type 'S'" part serves, there's absolutely no check for entering "S" in the code, only "E" for end.
On a side note: we're in C (basically), but it's still not a good idea to use C++ keywords as identifiers. Let new and operator be reserved. Call that variable op.
Also, as a design improvement, you can abstract away the big switch statement into the calculator class, and that way you could write something like [myCalc performOp:'+' withNumber:number]; etc.

Related

Simple Math App

I am new in Objective C, and I need to do a basic math application within a 5 times loop. Users will need to state what operation will perform (+,-,*,/) and the program will generates two random numbers to do math operations. Then the user will do the math and the program will compare his input with the correct answer. At the end the user will receive a score % and a custom message according to right or wrong answer. I am a bit stuck. First I did the program which generates two random numbers and run nicely. However when I added the rest of the code I have a warning message that says that the implementation is incomplete. I am also unable to see what is happening whit the else structure within the case because I received errors indicating "Expected expression" in each one of them.
Any help is very much appreciated.
Here is my code:
#import <Foundation/Foundation.h>
#interface myMath : NSObject
//methods
-(int) getRandomNumber;
-(void) add: (double) result;
-(void) subtract: (double) result;
-(void) multiply: (double) result;
-(void) divide: (double) result;
#end
#implementation myMath
//returns a random number between 1 and 100
-(int) getRandomNumber{
return (arc4random()%(100-1))+1;
}
#end
#interface Calculator : NSObject
#property double setaccumulator, accumulator; //Synt all methods.
#end
#implementation Calculator{
double accumulator;
}
-(void) setAccumulator: (double) value;
{ accumulator = value; }
-(void) clear
{ accumulator = 0; }
-(double) accumulator
{ return accumulator; }
-(void) add: (double) value
{ accumulator += value; }
-(void) subtract: (double) value
{ accumulator -= value; }
-(void) multiply: (double) value
{ accumulator *= value; }
-(void) divide: (double) value
{ accumulator /= value; }
#end
int main(int argc, const char * argv[]) {
#autoreleasepool {
myMath *myMathStuff;
myMathStuff = [[myMath alloc] init];
int rnum1 = [myMathStuff getRandomNumber];
int rnum2 = [myMathStuff getRandomNumber];
double result;
char operator;
Calculator *myCalculator = [[Calculator alloc]init];
int n, right, wrong, cont;
n = 0, right, wrong, cont = 0;
NSLog(#"The random numbers are %i and %i", rnum1, rnum2);
while (n <= 5){
NSLog(#"What operation do you want to perform? (+ . - . * . / .");
scanf(" %c", &operator);
[myCalculator setAccumulator:(double) rnum1];
switch (operator) {
case '+':
[myCalculator add: rnum2];
NSLog(#"Please type the addition result: ");
scanf("%lf", &result);
if (result == rnum1)
right =+1;
NSLog(#"Congratulations, you did it right!");
else
wrong =+1;
NSLog(#"Sorry, the addition result is: %.2f", [myCalculator accumulator]);
break;
case '-':
[myCalculator subtract: rnum2]
NSLog(#"Please type the subtraction: ");
scanf("%lf", &result);
if (result == rnum1)
right =+1;
NSLog(#"Congratulations, you did it right!");
else
wrong =+1,
NSLog(#"Sorry, the subtraction result is: %.2f", [myCalculator accumulator]);
break;
case '*':
[myCalculator multiply: rnum2];
NSLog(#"Please type the multiplication result: ");
scanf("%lf", &result);
if (result == rnum1)
right =+1;
NSLog(#"Congratulations, you did it right!");
else
wrong =+1,
NSLog(#"Sorry, the multiplication result is: %.2f", [myCalculator accumulator]);
break;
case '/':
[myCalculator divide: rnum2];
NSLog(#"Please type the division result: ");
scanf("%lf", &result);
if (result == rnum1)
right =+1;
NSLog(#"Congratulations, you did it right!");
else
wrong =+1,
NSLog(#"Sorry, the division result is: %.2f", [myCalculator accumulator]);
break;
default:
break;
}
++n;
}
NSLog(#"You were right %i", right);
NSLog(#"You were wrong %i", wrong);
if (right == 4)
NSLog(#"Excellent you have a perfect 100 percent score");
else if (right == 3)
NSLog(#"Good job you have a 80 percent score");
else if (right == 2)
NSLog (#"Well, you have a 60 percent score");
else if (right ==1)
NSLog(#"Sorry, you have received a 20 percent score");
}
return 0;
}
I made some changes on the myMath implementation and I also changed the lines where the "else" appears as I show below. I am still getting the expected expression. If somebody else can see what I am not seeing I would appreciate your input.
Part of the code I changed:
switch (operator) {
case '+':
[myMathStuff add: rnum2];
NSLog(#"Please type the addition result: ");
scanf("%lf", &result);
if (result == rnum1)
right =+1;
NSLog (#"Congratulations, you did it right!");
else {
wrong =+1;
NSLog (#"Sorry, the addition result is: %.2f", [myMathStuff accumulator]);
}
break;
I was able to find the solution.
You are getting implementation is incomplete because in your MyMath class you are saying that you have 5 methods at the class level, and only one of those (GetRandomNumber) is actually implemented.
You need to finish the contract - that is - code out what the other four methods are going to do (add, subtract, multiply, divide).

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.

complex number in Objective-C [duplicate]

For the following code,
-How does Objective-C know to add an "i" to complex numbers? When I defined "real" and "imaginary" as double values in the Complex.m file I figured Xcode would ONLY know that "real" and "imaginary" are double values.
-If I add an "i" to the end of a complex number in main.m file, for example, if I turn "myComplex.imaginary = 7;" into "myComplex.imaginary = 7i;" the output for that line becomes 0.00000i, if I add any other letter, the program will simply not run, why is this?
Basically it appears to me that the meaning of "real" and "imaginary" are already known to Xcode, the book I'm following did not specify this so I'm a little confused.
Also, I should note that I did not create the following code as I couldn't figure out the problem on my own, this code was copied from a member of my books forum.
// Complex.h
#include <Foundation/Foundation.h>
#interface Complex : NSObject
#property double real, imaginary;
-(void) print;
-(Complex *) add: (Complex *) complexNum;
-(Complex *) subtract: (Complex *) complexNum;
-(Complex *) multiply: (Complex *) complexNum;
-(Complex *) divide: (Complex *) complexNum;
#end
// Complex.m
#import "Complex.h"
#implementation Complex
#synthesize real, imaginary;
-(void) print
{
NSLog(#"%f + %fi", real, imaginary);
}
-(Complex *) add: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real + complexNum.real;
result.imaginary = imaginary + complexNum.imaginary;
return result;
}
-(Complex *) subtract: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real - complexNum.real;
result.imaginary = imaginary - complexNum.imaginary;
return result;
}
-(Complex *) multiply: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real * complexNum.real;
result.imaginary = imaginary * complexNum.imaginary;
return result;
}
-(Complex *) divide: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real / complexNum.real;
result.imaginary = imaginary / complexNum.imaginary;
return result;
}
#end
//
// main.m
// Complex
#include <Foundation/Foundation.h>
#import "Complex.h"
int main(int argc, const char *argv[]) {
#autoreleasepool {
Complex *myComplex = [[Complex alloc]init];
Complex *totalComplex = [[Complex alloc]init];
Complex *yourComplex = [[Complex alloc]init];
myComplex.real = 5.3;
myComplex.imaginary = 7;
[myComplex print];
NSLog(#"+");
yourComplex.real = 2.7;
yourComplex.imaginary = 4;
[yourComplex print];
NSLog(#"=");
totalComplex = [myComplex add: yourComplex];
[totalComplex print];
}
return 0;
}
Complex number types are defined in C99, which the modern version of Objective-C is a superset of. The actual syntax is like:
#include <complex.h>
...
complex double z = 2.7 + 3.4*I;
complex double w = 4.5 - 1.7*I;
complex double t = z*w;
printf("%g + %gi", creal(t), cimag(t));
That i suffix is an extension coming from GCC. The compiler (clang) used by Xcode has most features being compatible with GCC, thus you can write 3.4i and have no errors.
And for your questions,
How does Objective-C know to add an "i" to complex numbers?
If you mean the output, no Objective-C does not know to add an "i". It prints the "i" only because you told it to
-(void) print
{
NSLog(#"%f + %fi", real, imaginary);
// ^
}
if I turn "myComplex.imaginary = 7;" into "myComplex.imaginary = 7i;" the output for that line becomes 0.00000i
Because 7i is an imaginary number, and myComplex.imaginary is a "double", thus a real number. The C standard recommends that, when converting between real and imaginary numbers, you'll get zero (C99 §G.4.2/1). Thus effectively what you've written is myComplex.imaginary = 0.0;.
if I add any other letter, the program will simply not run, why is this?
Actually you can write things like 7.0if. Again, this is a C thing, which Objective-C has adapted. You are allowed to add an f to turn a decimal number from the the default type "double" to "float", and GCC adds an extra feature that you can add an i to turn a real number to an imaginary number. Other suffices like 7.0x will cause the compiler to stop because it doesn't know what x means.
C99 has added native support for complex numbers, so now they are as easy to handle as ordinary floating-point or integer numbers. No more ugly structs! Presumably by doing tricks with the floating-point representation of numbers, the _Complex_I and the equivalent I macro have a value that, when multiplied by a real number, results in a number of type double complex or float complex (complex is a new type modifier keyword, also introduced in C99). So with this new convenience feature, you can perform complex-number calculations in C as easily as
#include <complex.h>
double complex z1 = 2.0 + 3.0 * I;
double complex z2 = 1.5 - 2.0 * I;
double complex prod = z1 * z2;
printf("Product = %f + %f\n", creal(prod), cimag(prod));
Please check the GNU explanation about this as well.
The i suffix is a GNU extension to the C99 language, therefore it's non-standard. Nevertheless, both compilers used by Xcode (GCC and Clang) implement this extension.
(Sidenote: Xcode knows nothing about this. Please don't confuse the IDE with the compiler. Xcode itself doesn't perform compilation - the compilers behind it do.)
Here is class for operating with complex numbers I've developed for the purposes of my project. May be it will be useful to somebody. It contains standard addition, subtraction, multiplication and division methods. Moreover it has method for calculating modulus and argument of complex number. And, at last, it has class method for calculating turning factor (complex exponent) that is useful for "butterfly" algorithm when deal with fast Fourier transformation
#import <Foundation/Foundation.h>
#interface Complex : NSObject
#property double re, im;
-(Complex *)add :(Complex *) n;
-(Complex *)sub :(Complex *) n;
-(Complex *)mul :(Complex *) n;
-(Complex *)div :(Complex *) n;
+(Complex *)wkn :(int) k :(int) n;
-(double)mod;
-(double)arg;
#end
#import "Complex.h"
#implementation Complex
#synthesize re, im;
// Addition of two complex numbers
-(Complex *)add:(Complex *)n
{
Complex *res = [[Complex alloc]init];
res.re = re + n.re;
res.im = im + n.im;
return res;
}
// Subtraction of two complex numbers
-(Complex *)sub:(Complex *)n
{
Complex *res = [[Complex alloc]init];
res.re = re - n.re;
res.im = im - n.im;
return res;
}
// Multiplication of two complex numbers
-(Complex *)mul:(Complex *)n
{
Complex *res = [[Complex alloc]init];
res.re = re * n.re - im * n.im;
res.im = re * n.im + im * n.re;
return res;
}
// Division of two complex numbers
-(Complex *)div: (Complex *)n
{
Complex *res = [[Complex alloc]init];
double A = (pow(n.re, 2.0) + pow(n.im, 2.0));
res.re = (re * n.re - im * n.im) / A;
res.im = (im * n.re - re * n.im) / A;
return res;
}
// Modulus of complex number
-(double)mod
{
double res = sqrt(pow(re, 2.0) + pow(im, 2.0));
return res;
}
// Argument of complex number
-(double)arg
{
double res; int quad;
if (re == 0 && im > 0) res = M_PI_2;
else if (re == 0 && im < 0) res = 3 * M_PI_2;
else
{
if (re > 0 && im >= 0) quad = 1;
else if (re < 0 && im >= 0) quad = 2;
else if (re < 0 && im < 0) quad = 3;
else if (re > 0 && im < 0) quad = 4;
double temp = atan(im / re);
switch (quad)
{
case 1:
res = temp;
break;
case 4:
res = 2 * M_PI + temp;
break;
case 2: case 3:
res = M_PI + temp;
break;
}
}
return res;
}
// Turning factor calculation for "butterfly" FFT algorithm
+(Complex *)wkn:(int)k :(int)n
{
Complex *res = [[Complex alloc]init];
res.re = cos(2 * M_PI * k / n);
res.im = -sin(2 * M_PI * k / n);
return res;
}
#end
Thanks for your patience )
There are two serious mistakes in class Complex implementation - complex numbers are multiplied and divided in absolutely wrong way! It's absolutely not enough simply multiply or divide real and imaginary parts of two complex numbers. You have to use multiplication and dividing formulas in that case, I think Google contains a lot entries about it. Right now it is erroneous code and it have to be rewritten.
For multiplication it must be something like this
-(Complex *)mul:(Complex *)n
{
Complex *res = [[Complex alloc]init];
res.re = re * n.re - im * n.im;
res.im = re * n.im + im * n.re;
return res;
}

Are "Complex Numbers" already defined in Objective-C?

For the following code,
-How does Objective-C know to add an "i" to complex numbers? When I defined "real" and "imaginary" as double values in the Complex.m file I figured Xcode would ONLY know that "real" and "imaginary" are double values.
-If I add an "i" to the end of a complex number in main.m file, for example, if I turn "myComplex.imaginary = 7;" into "myComplex.imaginary = 7i;" the output for that line becomes 0.00000i, if I add any other letter, the program will simply not run, why is this?
Basically it appears to me that the meaning of "real" and "imaginary" are already known to Xcode, the book I'm following did not specify this so I'm a little confused.
Also, I should note that I did not create the following code as I couldn't figure out the problem on my own, this code was copied from a member of my books forum.
// Complex.h
#include <Foundation/Foundation.h>
#interface Complex : NSObject
#property double real, imaginary;
-(void) print;
-(Complex *) add: (Complex *) complexNum;
-(Complex *) subtract: (Complex *) complexNum;
-(Complex *) multiply: (Complex *) complexNum;
-(Complex *) divide: (Complex *) complexNum;
#end
// Complex.m
#import "Complex.h"
#implementation Complex
#synthesize real, imaginary;
-(void) print
{
NSLog(#"%f + %fi", real, imaginary);
}
-(Complex *) add: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real + complexNum.real;
result.imaginary = imaginary + complexNum.imaginary;
return result;
}
-(Complex *) subtract: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real - complexNum.real;
result.imaginary = imaginary - complexNum.imaginary;
return result;
}
-(Complex *) multiply: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real * complexNum.real;
result.imaginary = imaginary * complexNum.imaginary;
return result;
}
-(Complex *) divide: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real / complexNum.real;
result.imaginary = imaginary / complexNum.imaginary;
return result;
}
#end
//
// main.m
// Complex
#include <Foundation/Foundation.h>
#import "Complex.h"
int main(int argc, const char *argv[]) {
#autoreleasepool {
Complex *myComplex = [[Complex alloc]init];
Complex *totalComplex = [[Complex alloc]init];
Complex *yourComplex = [[Complex alloc]init];
myComplex.real = 5.3;
myComplex.imaginary = 7;
[myComplex print];
NSLog(#"+");
yourComplex.real = 2.7;
yourComplex.imaginary = 4;
[yourComplex print];
NSLog(#"=");
totalComplex = [myComplex add: yourComplex];
[totalComplex print];
}
return 0;
}
Complex number types are defined in C99, which the modern version of Objective-C is a superset of. The actual syntax is like:
#include <complex.h>
...
complex double z = 2.7 + 3.4*I;
complex double w = 4.5 - 1.7*I;
complex double t = z*w;
printf("%g + %gi", creal(t), cimag(t));
That i suffix is an extension coming from GCC. The compiler (clang) used by Xcode has most features being compatible with GCC, thus you can write 3.4i and have no errors.
And for your questions,
How does Objective-C know to add an "i" to complex numbers?
If you mean the output, no Objective-C does not know to add an "i". It prints the "i" only because you told it to
-(void) print
{
NSLog(#"%f + %fi", real, imaginary);
// ^
}
if I turn "myComplex.imaginary = 7;" into "myComplex.imaginary = 7i;" the output for that line becomes 0.00000i
Because 7i is an imaginary number, and myComplex.imaginary is a "double", thus a real number. The C standard recommends that, when converting between real and imaginary numbers, you'll get zero (C99 §G.4.2/1). Thus effectively what you've written is myComplex.imaginary = 0.0;.
if I add any other letter, the program will simply not run, why is this?
Actually you can write things like 7.0if. Again, this is a C thing, which Objective-C has adapted. You are allowed to add an f to turn a decimal number from the the default type "double" to "float", and GCC adds an extra feature that you can add an i to turn a real number to an imaginary number. Other suffices like 7.0x will cause the compiler to stop because it doesn't know what x means.
C99 has added native support for complex numbers, so now they are as easy to handle as ordinary floating-point or integer numbers. No more ugly structs! Presumably by doing tricks with the floating-point representation of numbers, the _Complex_I and the equivalent I macro have a value that, when multiplied by a real number, results in a number of type double complex or float complex (complex is a new type modifier keyword, also introduced in C99). So with this new convenience feature, you can perform complex-number calculations in C as easily as
#include <complex.h>
double complex z1 = 2.0 + 3.0 * I;
double complex z2 = 1.5 - 2.0 * I;
double complex prod = z1 * z2;
printf("Product = %f + %f\n", creal(prod), cimag(prod));
Please check the GNU explanation about this as well.
The i suffix is a GNU extension to the C99 language, therefore it's non-standard. Nevertheless, both compilers used by Xcode (GCC and Clang) implement this extension.
(Sidenote: Xcode knows nothing about this. Please don't confuse the IDE with the compiler. Xcode itself doesn't perform compilation - the compilers behind it do.)
Here is class for operating with complex numbers I've developed for the purposes of my project. May be it will be useful to somebody. It contains standard addition, subtraction, multiplication and division methods. Moreover it has method for calculating modulus and argument of complex number. And, at last, it has class method for calculating turning factor (complex exponent) that is useful for "butterfly" algorithm when deal with fast Fourier transformation
#import <Foundation/Foundation.h>
#interface Complex : NSObject
#property double re, im;
-(Complex *)add :(Complex *) n;
-(Complex *)sub :(Complex *) n;
-(Complex *)mul :(Complex *) n;
-(Complex *)div :(Complex *) n;
+(Complex *)wkn :(int) k :(int) n;
-(double)mod;
-(double)arg;
#end
#import "Complex.h"
#implementation Complex
#synthesize re, im;
// Addition of two complex numbers
-(Complex *)add:(Complex *)n
{
Complex *res = [[Complex alloc]init];
res.re = re + n.re;
res.im = im + n.im;
return res;
}
// Subtraction of two complex numbers
-(Complex *)sub:(Complex *)n
{
Complex *res = [[Complex alloc]init];
res.re = re - n.re;
res.im = im - n.im;
return res;
}
// Multiplication of two complex numbers
-(Complex *)mul:(Complex *)n
{
Complex *res = [[Complex alloc]init];
res.re = re * n.re - im * n.im;
res.im = re * n.im + im * n.re;
return res;
}
// Division of two complex numbers
-(Complex *)div: (Complex *)n
{
Complex *res = [[Complex alloc]init];
double A = (pow(n.re, 2.0) + pow(n.im, 2.0));
res.re = (re * n.re - im * n.im) / A;
res.im = (im * n.re - re * n.im) / A;
return res;
}
// Modulus of complex number
-(double)mod
{
double res = sqrt(pow(re, 2.0) + pow(im, 2.0));
return res;
}
// Argument of complex number
-(double)arg
{
double res; int quad;
if (re == 0 && im > 0) res = M_PI_2;
else if (re == 0 && im < 0) res = 3 * M_PI_2;
else
{
if (re > 0 && im >= 0) quad = 1;
else if (re < 0 && im >= 0) quad = 2;
else if (re < 0 && im < 0) quad = 3;
else if (re > 0 && im < 0) quad = 4;
double temp = atan(im / re);
switch (quad)
{
case 1:
res = temp;
break;
case 4:
res = 2 * M_PI + temp;
break;
case 2: case 3:
res = M_PI + temp;
break;
}
}
return res;
}
// Turning factor calculation for "butterfly" FFT algorithm
+(Complex *)wkn:(int)k :(int)n
{
Complex *res = [[Complex alloc]init];
res.re = cos(2 * M_PI * k / n);
res.im = -sin(2 * M_PI * k / n);
return res;
}
#end
Thanks for your patience )
There are two serious mistakes in class Complex implementation - complex numbers are multiplied and divided in absolutely wrong way! It's absolutely not enough simply multiply or divide real and imaginary parts of two complex numbers. You have to use multiplication and dividing formulas in that case, I think Google contains a lot entries about it. Right now it is erroneous code and it have to be rewritten.
For multiplication it must be something like this
-(Complex *)mul:(Complex *)n
{
Complex *res = [[Complex alloc]init];
res.re = re * n.re - im * n.im;
res.im = re * n.im + im * n.re;
return res;
}

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!