开发者

Quick Multiplication Question - Cocoa

I'm still learn开发者_StackOverflow社区ing, and I'm just stuck. I want the user to enter any number and in result, my program will do this equation:

x = 5*y

(y is the number the user adds, x is outcome)

How would I do this? I'm not sure if I'm suppose to add in an int or NSString. Which should I use, and should I enter anything in the header files?


I'm not sure if I'm suppose to add in an int or NSString.

Well, one of these is a numeric type and the other is a text type. How do you multiply text? (Aside from repeating it.)

You need a numeric type.

I would caution against int, since it can only hold integers. The user wouldn't be able to enter “0.5” and get 2.5; when you converted the “0.5” to an int, the fractional part would get lopped off, leaving only the integral part, which is 0. Then you'd multiply 5 by 0, and the result you return to the user would be 0.

Use double. That's a floating-point type; as such, it can hold fractional values.

… should I enter anything in the header files?

Yes, but what you enter depends on whether you want to use Bindings or not (assuming that you really are talking about Cocoa and not Cocoa Touch).

Without Bindings, declare an outlet to the text field you're going to retrieve the multiplier from, and another to the text field you're going to put the product into. Send the input text field a doubleValue message to get the multiplier, and send the output text field a setDoubleValue: message with the product.

With Bindings, declare two instance variables holding double values—again, one for the multiplier and one for the product—along with properties exposing the instance variables, then synthesize the properties, and, finally, bind the text fields' value bindings to those properties.


If you're retrieving the NSString from a UI, then it's pretty simple to do:

NSString * answer = [NSString stringWithFormat:@"%d", [userInputString integerValue]*5];


This can be done without any objective C. That is, since Objective-C is a superset of C, the problem can be solved in pure C.

#include <stdio.h>
int main(void)
{
    int i;
    fscanf(stdin, "%d", &i);
    printf("%d\n", i * 5);
}

In the above the fscanf takes care of converting the character(s) read on the standard input to a number and storing it in i.

However, if you had characters from some other source in a char* and needed to convert them to an int, you could create an NSString* with the – initWithCString:encoding: and then use its intValue method, but in this particular problem that simply isn't needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜