2

我正在通过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;
}
4

2 回答 2

4

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

但是对于初学者来说,您发布的代码片段(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);
}

高温高压

于 2012-12-16T10:40:52.263 回答
2

您的 scanf 语法错误,应该是

scanf("%i",&number) //for integer
于 2014-08-29T19:06:05.397 回答