2016-06-11 38 views
-1

我正在解決代碼中的this問題,並且我用C++編寫了代碼。這是快速的(但壞)解決方案:C++程序在不同的機器上產生不同的輸出

#include <stdio.h> 
#include <iostream> 
#include <algorithm> 
#include <string.h> 
#include <cmath> 

using namespace std; 

int main() 
{ 
    int n,r,c,temp,len,i; 
    char str[100]; 
    char rem; 
    string res; 

    cin >> n; 
    while(n--) 
    { 
     r = c = -1; 
     res = ""; 

     scanf("%s",str); 
     sscanf(str, "R%dC%d",&r,&c); 

     if(r != -1 && c != -1) 
     { 
      /* RC type */ 
      temp = c; 
      if(c%26 == 0) 
       temp--; 
      while(temp) 
      { 
       rem = 'A' + (temp%26 - 1); 
       res = res + rem; 
       temp = temp/26; 
      } 
      if(c%26 == 0) 
       res.at(0) = res.at(0) + 1; 

      reverse(res.begin(), res.end()); 
      cout << res << r << endl; 
     } 
     else 
     { 
      /* normal type */ 
      len = strlen(str); 
      r = 0; 
      c = 0; 
      temp = 0; 
      for(i=len-1;i>=0;i--) 
      { 
       if(str[i] >= '0' && str[i] <= '9') 
       { 
        r = r + pow(10,len-i-1) * (str[i] - '0'); 
       } 
       else 
       { 
        c = c + pow(26,temp)*(str[i] - 'A' + 1); 
        temp++; 
       } 
      } 
      cout << "R" << r << "C" << c << endl; 
     } 
    } 
    return 0; 
} 

如果這是輸入:

2 
R23C55 
BC23 

我的Linux 64位GCC給出了這樣的輸出:

BC23 
R23C55 

但網上法官給出這樣的輸出:

BC23 
R23C54 

我已經使用了正確的括號,沒有無限增量/減量運算符,以確保在兩臺機器上的事物完全相同的順序od評估,但仍然存在導致未定義評估的問題。任何人都可以請幫助什麼聲明有未定義的行爲。 AFAIK,解決方案沒有這樣的說法。請幫忙。

編輯 我用ceil()pow()各地,並通過了測試案例。雖然,我現在很害怕。我現在擔心如何確定從pow()返回的值,因爲there is a good reason of not implementing pow to return int type.

+3

它不是'C/C++',它只是'C++'。 – pzaenger

+1

你應該做一些調試。 –

+0

@OliverCharlesworth:過去1個小時我一直在撓頭,但無論是我忽略了某些事情還是僅僅是錯誤... –

回答

1

Maxim Sabyanin的評論可能是一種可能的解決方案。如果你只對整數感興趣,那麼要麼執行pow的結果或ceil。我以前遇到類似的問題。你可以寫一個簡單的實現戰俘如下圖所示

int exponent(int base_number, int power) 
{ 
    int i;//multiplication counter 
    int current_product=1; 
    for(i=0; i<power; i=i+1) 
    { 
     current_product=current_product*base_number; 
    } 
    return current_product; 
} 
0

我用ceil()pow()各地,並通過了測試案例。

這是在這種情況下避免pow的好理由。實現一個可以與整型類型一起工作並且不會遇到浮點精度問題的函數並不難。

int int_pow(int x, unsigned int n) 
{ 
    int ret = 1; 
    while (n--) 
    { 
     ret *= x; 
    } 
    return ret; 
} 

請注意,如果這成爲性能瓶頸,則可以使用稍微修改後的版本。

int int_pow(int x, unsigned int n) 
{ 
    if (n == 0) 
    { 
     return 1; 
    } 

    return (int_pow(x, n/2) * (n%2 == 0 ? 1 : x)); 
} 
相關問題