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)値を与えることはなく、(b)設定してテストしyたときにループが実行されることはありません。これはすぐに失敗し、ループに入りません。count = 1count == 3

y(a)の場合、私はあなたがどこから来ると期待しているのかを推測することしかできませんでし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ます。

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

于 2012-12-16T10:40:52.263 に答える
2

あなたのscanf構文は間違っています

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