为什么即使有条件我的循环也会终止?

时间:2019-02-27 04:30:51

标签: c arrays loops break

我试图获取用户输入并将其存储在数组Fib [i]中。之后,打印Fib [i]数组。当用户输入-1时,循环将退出,程序将结束。但是我的代码无法打印或终止。

int getNumberOfFrames(NSURL *url)
{
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];

    AVAssetTrack *videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];

    AVAssetReaderTrackOutput *readerVideoTrackOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:videoTrack outputSettings:nil];

    AVAssetReader *assetReader = [AVAssetReader assetReaderWithAsset:asset error:nil];
    [assetReader addOutput:readerVideoTrackOutput];

    [assetReader startReading];

    int nframes = 0;
    for (;;)
    {
        CMSampleBufferRef buffer = [readerVideoTrackOutput copyNextSampleBuffer];
        if (buffer == NULL)
        {
            break;
        }

        CMFormatDescriptionRef formatDescription = CMSampleBufferGetFormatDescription(buffer);
        CMMediaType mediaType = CMFormatDescriptionGetMediaType(formatDescription);
        if (mediaType == kCMMediaType_Video)
        {
            nframes++;
        }

        CFRelease(buffer);
    }

    return nframes;
}

用户输入:

import matplotlib.pyplot as plt

plt.plot(data['datetime'], data['step'], color="orange")
plt.xticks(rotation='vertical')
plt.grid(True)

预期输出:

#include <stdio.h>

double Fib[50];//globally declared  
int fib(int n)
{
    int i;

    for(i=0; i<50; i++)
    {   
        scanf("%d", &Fib[i]); 
        if(i==-1)
         break;
       //printf("numbers entered %d\n", Fib[i]); // <- doesn't terminate if printf is here
    }
        printf("numbers entered %d\n", Fib[i]); //doesn't print anything??

}
int main()
{
    int i, n;
//calling the function
    fib(n);

return 0;

}

2 个答案:

答案 0 :(得分:4)

第一个问题:您将Fib声明为double的数组:

double Fib[50];

但是您使用%d来读取值,这是为了读取int

scanf("%d", &Fib[i]); 

使用错误的格式说明符会调用undefined behavior。您大概想存储整数,因此将数组更改为int

int Fib[50];

接下来是您的阵列突破条件:

if(i==-1)

i是您的数组索引,范围从0到49,所以永远不会如此。您想在用户输入-1时停止,并且该值将在Fib[i]中:

if(Fib[i]==-1)

最后,打印数组:

printf("numbers entered %d\n", Fib[i]);

这不会打印数组。它仅在i的最后一个索引处打印元素,并且该索引处的值始终为-1。您需要一个单独的循环来打印值:

int j;
printf("numbers entered:\n");
for (j=0; j<i; j++) {
    printf("%d\n", Fib[j]);
}

答案 1 :(得分:1)

此代码具有许多编写标准问题的代码,但是您似乎是新手,所以为了您的理解,我进行了最小的更改

#include <stdio.h>

double Fib[50];//globally declared  
int fib(int n)
{
    int i,j;

    for(i=0; i<50; i++)
    {   
        scanf("%lf", &Fib[i]); 
        if(Fib[i]==-1)
         break;
    }  
    printf("numbers entered \n");
    for(int j=0;j<i;j++)
    {
        printf("%lf\n",Fib[j]);
    }
}
int main()
{
    int i, n;
    fib(n);
    return 0;

}