我正在通过 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/