簡體   English   中英

在int main()中多次調用的函數中聲明變量(在C中)

[英]Declaring variables in functions that are called more than once in int main() (in C)

如標題中所述,我要處理一個在main中多次調用的函數,其目的是對字符數組中的元音進行計數,並且僅在第一次調用時結果才正確。 之后,它不是從零開始,而是從中斷的地方開始計數,從而導致錯誤的結果。

這是功能:

int function(char *pointer, int num_of_elements)

{
    int i=0;
    if (num_of_elements==0) return i;
    if ((*pointer== 'a') || (*pointer== 'A') || (*pointer== 'e') || (*pointer== 'E') || (*pointer== 'i') || (*pointer== 'I' )||( *pointer=='o') || (*pointer =='O') || (*pointer== 'u') || (*pointer== 'U')) {i++;}
    pointer++;
    num_of_elements--;
    return function(pointer,num_of_elements);
} 

指針指向字符數組,變量i為計數器。

您必須返回i的總和以及function的遞歸調用的結果。 像這樣修改您的代碼:

#include <ctype.h>

int function(char *pointer, int num_of_elements)
{
    if (num_of_elements==0)
        return 0;

    char c = tolower( *pointer );
    int i = ( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ) ? 1 : 0;
    pointer++;
    num_of_elements--;
    return i + function( pointer, num_of_elements );
}

我建議循環解決您的問題,並使用tolower函數:

#include <ctype.h>

int function(char *pointer, int num_of_elements)
{
    int count = 0;
    for ( int i = 0; i < num_of_elements; i++, pointer ++)
    {
       char c = tolower( *pointer );
       if ( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )
           count ++;
   }
   return count;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM