1. 程式人生 > >NOIP 2018普及組複賽第1題答案詳解

NOIP 2018普及組複賽第1題答案詳解

NOIP 2018普及組複賽第1題.jpg

一、C程式

###解法一:用gets()函式

#include <stdio.h>
#include <string.h>

int main()
{
    // 將控制檯的資料重定向到檔案裡
    freopen("title.in", "r", stdin);
    freopen("title.out", "w", stdout);

    char s[100];
    gets(s);
    int total = 0;
    printf("%d\n", sizeof(s));

    // 這裡只能用strlen,不能用sizeof
    // 因為sizeof(s)=sizeof(s)/sizeof(char)=100
    for(int i = 0; i < strlen(s); i++)
    {
        if(s[i] != ' ')
        {
            total++;
        }
    }

    printf("%d", total);
    return 0;
}

###解法二:用scanf()函式

#include <stdio.h>
#include <string.h>

int main()
{
    // 將控制檯的資料重定向到檔案裡
    freopen("title.in", "r", stdin);
    freopen("title.out", "w", stdout);

    char s[100];
    // 不能使用scanf("%s",s);因為遇到第一個空格就會結束
    // 符號^表示取反,[^\n]表示除了換行符,其他的字元都可以讀取
    scanf("%[^\n]", s);
    int total = 0;

    // 這裡只能用strlen,不能用sizeof
    // 因為sizeof(s)=sizeof(s)/sizeof(char)=100
    for(int i = 0; i < strlen(s); i++)
    {
        if(s[i] != ' ')
        {
            total++;
        }
    }

    printf("%d", total);
    return 0;
}

二、C++程式

#include <iostream>
#include <stdio.h>  // freopen和stdin、stdout要用到此標頭檔案
using namespace std;

int main()
{
    // 將控制檯的資料重定向到檔案裡
    freopen("title.in", "r", stdin);
    freopen("title.out", "w", stdout);

    string s;
    getline(cin, s);
    int total = s.length();
    // for迴圈裡面的s.length()不要寫成total,因為total是不斷減小的
    for(int i = 0; i < s.length(); i++)
    {
        if(s[i] == ' ')
        {
            total--;
        }
    }

    cout << total << endl;
    return 0;
}

三、總結

本題考察的知識點有兩個:
(1)輸入帶空格的字串
常用的scanf和cin,遇到第一個空格就會停止輸入。
C語言可以使用gets()輸入帶空格的字串。當然使用scanf(“%[^\n]”, s)也可以。
C++可以使用getline()輸入帶空格的字串

(2)求字串的長度
C語言的字元陣列可以使用strlen(s);
C++的string可以使用s.length()或s.size()。

少兒程式設計QQ群:581357582
少兒英語QQ群:952399366
公眾號.jpg