福州大學上機題——求數組中給定區間內數值的和

福州大學上機題——求數組中給定區間內數值的和

題目描述:
輸入一個數組,然後求出任意給定的區間內數值的和。

#include<iostream>
using namespace std;
int main() {
	int n;
	cout << "輸入數字個數:";
	cin >> n;
	int* num = new int[n];
	cout << "輸入數組:";
	for (int i = 0;i < n;i++)
		cin >> num[i];
	int a, b;
	cout << "輸入查詢範圍[a,b]:";
	cin >> a >> b;
	int sum = 0;
	for (int i = a;i <= b;i++)
		sum += num[i];
	cout << "區間內和爲:" << sum << endl;
	return 0;
}

運行測試結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章