objective-c - 与 scanf 函数一起使用

标签 objective-c xcode4 scanf

我正在通过 objective-C 进行 scanf 倒计时,因此程序将从您输入的任何数字开始倒计时。但是,代码中有一个烦人的语义错误:格式字符串未使用数据参数。此外,该程序不会倒计时,它只会在我输入数字后将输出显示为零。

#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;
}

最佳答案

你不说你遇到了什么麻烦,或者你试图解决什么问题,所以人们很难帮助你。

但对于初学者来说,您发布的代码片段 (a) 从未给出 y一个值和 (b) 循环将永远不会按照您设置的方式执行 count = 1然后测试 count == 3 - 这将立即失败并且不会进入循环。

对于 (a),我只能猜测您期望的位置 y来自,对于 (b) 你可能是说 count <= 3 - 即循环 3 次?

评论后补遗

好的,让我们稍微重写一下您的代码并添加一些注释。 for循环可以重写为 while循环,在你的情况下,这看起来像:

count = 1; // initialize
while (count == 3) // Test, will fail immediately, did you mean count <= 3?
{
   NSLog(@"enter a number");
   scanf("%i", &x);
   // At this point you have set x to a value
   // however y has no value - as it is a local variable it has some random value
   // the next line calculates `y%x`, and without a value for y this calculation
   // is meaningless. Did you mean to read in both x and y? E.g. scanf("%i%i", &x, &y)?
   // Note you should also check the return value from scanf, it is the number of items
   // successfully converted - while you may "enter a number" your user might type
   // "sixteen", which is a number to them but scanf won't parse it with %i!
   if (y%x == 0)
      NSLog(@"%i is evenly divisible by %i", y, x);
   else
      NSLog(@"%i is NOT evenly divisible by %i", y, x);

   count++; // increment
}

进行上述更改并恢复到 for给出:

for (count = 1; count <= 3; count++)
{
   NSLog(@"enter two numbers");
   int numberRead = scanf("%i%i", &x, &y);

   if (numberRead != 2)
      NSLog(@"error, unable to parse two numbers");
   else if (y%x == 0)
      NSLog(@"%i is evenly divisible by %i", y, x);
   else
      NSLog(@"%i is NOT evenly divisible by %i", y, x);
}

HTH

关于objective-c - 与 scanf 函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13898496/

相关文章:

objective-c - 具有回调方法的 IOS Grand Central Dispatch

build - 如何防止在 iPad 上安装应用程序

c - 将变量直接传递给 C 中的函数?

c - 最大限度地减少 sscanf 的内存消耗

ios - 通过触摸结束事件处理重叠按钮?

c++ - 在 Cocoa 中正确实现四元数计算?

ios - 如何在 Xcode 4.2 中禁用 CoreData 的无反向关系警告?

c - 输入一个短语来 scanf ("%c", &ch)...(%c 表示序列,不适用于单个符号)

ios - viewDidAppear 调用了在 iOS8 中被关闭的 View Controller

无法让 modf() 工作