華為機試—整數相除,華為整數相除

來源:互聯網
上載者:User

華為機試—整數相除,華為整數相除
兩個整數相除,將結果用字串返回。如果是迴圈小數,將迴圈的位用括弧括起來。

函數原型為 void div(const int a,const int b,char *str)

輸入:1 3

輸出:0.(3)


#include<iostream>#include<string>using namespace std;int maxn = 100; //設定字串的最大位元int reminder_exist[10000];int reminder_pos[10000];void div(const int a, const int b, char *str){int numerator,denominator,quotient, reminder, outcnt = 0;int flag = 0; //負數標誌memset(reminder_exist, 0, sizeof(reminder_exist));memset(reminder_pos, 0, sizeof(reminder_pos));  numerator = a; //定義const int,由於要改變分子分母,所以我們通過中間變數轉化denominator = b;if(a*b < 0)flag = 1;//有負數//將分子和分母變成整數numerator = numerator < 0 ? -numerator:numerator; denominator = denominator < 0 ? -denominator:denominator;quotient = numerator/denominator;reminder = numerator%denominator;   int integer = quotient;//找出迴圈int cycle_pos = maxn; //迴圈的位置int i = 0;for(i = 0; i <= maxn; i++){//找出餘數相等的情況,求出重複持續時間if(reminder_exist[reminder]){cycle_pos = reminder_pos[reminder];break;}else{reminder_exist[reminder] = 1;reminder_pos[reminder] = i;}numerator = reminder *10;quotient = numerator/denominator;reminder = numerator%denominator; str[outcnt++] = quotient + '0'; //將更新的商存入字串中}str[outcnt++] = '\0';if(!flag)cout << integer << "." ;elsecout << "-" << integer << ".";for(int j = 0; j < cycle_pos; j++)cout << str[j];cout << "(";for(j = cycle_pos; j < i;j++)cout <<  str[j];cout << ")" << endl;}int main(){int a,b;char s[100];while(cin >> a >> b){div(a,b,s);}cout<<endl;return 0;}


測試結果,可能想的不周全,歡迎查漏補缺:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.