Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรมหาว่าปีใดอยู่ในศตวรรษที่เท่าไหร่ใน C++


ในบทเรียนนี้ เราจะเขียนโปรแกรมหาว่าปีใดปีหนึ่งอยู่ในศตวรรษที่เท่าไหร่

กฎการหาศตวรรษ

  • ปี 1-100 → ศตวรรษที่ 1
  • ปี 101-200 → ศตวรรษที่ 2
  • ปี n: ถ้า n % 100 == 0 → ศตวรรษที่ n/100, มิฉะนั้น → n/100 + 1

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

void find_century(int year) {
    if (year <= 0) {
        cout << "0 and negative not allowed for a year";
    } else if (year <= 100) {
        cout << "1st century\n";
    } else if (year % 100 == 0) {
        cout << year / 100 << " century";
    } else {
        cout << year / 100 + 1 << " century";
    }
}

int main() {
    int year = 2001;
    find_century(year);
    return 0;
}

ผลลัพธ์

21 century

ตัวอย่างเพิ่มเติม

YearCentury
190019th
190120th
200020th
200121st
202421st

สูตรคัดสั้น

century = (year - 1) / 100 + 1

ทำงานได้ทุกกรณี ไม่ต้องเช็คเงื่อนไขแยก