你没有说你遇到了什么麻烦,或者你试图解决什么问题,所以人们很难帮助你。
但是对于初学者来说,您发布的代码片段(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);
}
高温高压