我正在通过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;
}
答案 0 :(得分:4)
你没有说你遇到了什么麻烦,或者你试图解决它的问题,所以人们很难帮助你。
但是对于初学者来说,你发布的代码片段(a)永远不会给y
一个值;(b)循环永远不会在你设置count = 1
然后测试{{1}时执行} - 将立即失败而不进入循环。
对于(a)我只能猜到你期望count == 3
来自哪里,因为(b)你可能意味着y
- 即循环3次?
评论后的附录
好的,让我们重新编写你的代码并添加一些注释。 count <= 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
HTH
答案 1 :(得分:2)
你的scanf语法错误应该是
scanf("%i",&number) //for integer