简单的Objective-C程序不起作用

时间:2011-08-09 14:39:11

标签: objective-c

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    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", number, triangularNumber);

    [pool drain];
    return 0;
}

写一个整数时的输出是:

Triangular Number 0 is 0

2 个答案:

答案 0 :(得分:2)

您的输入数字为0,并且for循环中的条件从1开始。因此,循环永远不会执行。

答案 1 :(得分:0)

应该是:

for (n = 1; n <= number; ++n)  {
        triangularNumber += n;
        NSLog(@"Triangular Number %i is %i", number, triangularNumber);
}

在编写它的方式中,它被解析为:

for (n = 1; n <= number; ++n)  {
    triangularNumber += n;
}
NSLog(@"Triangular Number %i is %i", number, triangularNumber);

由于输入(数字)为0(如打印所示),循环不会发生,但是打印了该行。