C++ 中交替左右移動 N 步後的位置
在這個問題中,我們給出三個整數 N、A 和 B。一個人站在座標 0 處,移動
向右移動 A 步,然後向左移動 B 步。然後再次向右移動。我們的任務是在 N 次移動後列印元素的最終位置。
讓我們舉個例子來理解這個問題,
輸入 - N = 4,A = 3,B = 1
輸出 -
解釋 -
1st move -> right 3, +3 2nd move -> left 1, -1 3rd move -> right 3, +3 4th move -> left 1, -1. Position after 4 moves, +3-1+3-1 = 4.
為了解決這個問題,我們必須找到這個人走過的總步數,將向右的步數視為正數,向左的步數視為負數。所有奇數步都向右移動,偶數步都向左移動。
總步數將根據以下公式計算:
Steps = [((n+1)/2)*a - (n/2)*b]
示例
程式展示了我們解決方案的示例:
#include <iostream>
using namespace std;
void finalPosition(int n, int a, int b) {
int steps = {((n + 1)/2)*a - (n/2)*b};
cout<<steps;
}
int main() {
int N=4, A=3, B=1;
cout<<"The final position of the person after "<<N<<" steps is ";
finalPosition(N,A,B);
return 0;
}輸出
The final position of the person after 4 steps is 4
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP