本文實例講述了C++求四個正整數最大公約數的方法。分享給大家供大家參考,具體如下:
/** 作 者: 劉同賓* 完成日期:2012 年 11 月 16 日* 版 本 號:v1.0** 輸入描述: 輸入四個正整數,輸出其最大公約數。* 問題描述:* 程序輸出:* 問題分析:略* 算法設計:略*/#include<iostream>using namespace std;int f(int,int);int g(int,int,int,int);int main(){ int a,b,c,d; cout<<"請輸入四個正整數:"<<endl; cin>>a>>b>>c>>d; cout<<"最大公約數為:"<<g(a,b,c,d)<<endl; return 0;}int f(int a,int b){ int m; while(b>0) { m=a%b; a=b; b=m; } return a;}int g(int a,int b,int c,int d){ int i,j,k; i=f(a,b); j=f(c,d); k=f(i,j); return k;}
運行效果如下圖所示:
希望本文所述對大家C++程序設計有所幫助。