2017-03-15 43 views
0

我試圖調試我的C++程序的標準輸入作爲C++向量輸入 - 運行時錯誤 - 調試超時 - 第一個for循環失敗

2 1 /newline/ 
4 

輸出調試器(onlinegdb)的: - 雖然第二行讀取了另一組由問題提供的輸入;此時,向量arr未顯示輸出4 set args 讀取/home/a.out...done中的符號。 (gdb)繼續
程序未運行。
(GDB)運行

Starting program: /home/a.out </home/input.txt         
2 1 

P.S. The program successfully compiles and runs for user provided input 

3 2 
3 
4 

P.S.那麼,爲什麼程序中的第一個循環並沒有正確執行?

源代碼 -

#include <cmath> 
#include <cstdio> 
#include <vector> 
#include <iostream> 
#include <algorithm> 
using namespace std; 

int main() { 
    int m; 
    cin>>m; 
    int t; 
    cin>>t; 
    cout<<m<<" "<<t<<"\n"; 
    int sum=0; 
    vector<int> arr(t); 
    for(int i=0;i<t;i++) 
     cin>>arr[i];    //arr[i]=k digit nos 
    for(int i=0;i<t;i++) 
     cout<<arr[i]<<" "; 
    int comb(int a, int b);   //6,2 

    for(int i=0;i<t;i++) 
    { 
     if(m==arr[i]){ 
      cout<<m<<" a "<<9*pow(10,m-1)<<"\n"; 
     } 
     if(m>arr[i]){ 
      cout<<m<<" b "<<9*pow(10,m-1)<<"\n"; 
     } 
     if(m<arr[i]){ 
      /*if(m==arr[i]-1){ 
      cout<<m<<" c "<<9*pow(10,arr[i]-1)-9<<"\n"; 
      } 
      else{*/ 
      sum=pow(10,arr[i])-1; 
      for(int j=arr[i]-1;j>m;j++) 
       sum=sum-comb(arr[i],j)*pow(9,arr[i]-j+1); 
      cout<<" d "<<sum<<"\n"; 
      //} 
     } 
    } 
    //for m upto 10^4, k<=10^5; else k=10^5 
    return 0; 
} 
int comb(int a, int b) {  //6,2 
     int j=1; 
     int s=a; 
     for(int k=a-1;k>b;k--)  //5,4,3 
      s=s*k; 
     for(int l=1;l<=b;l++) 
      s=s/l; 
     return s; 
    } 
    //It is a problem involving displaying number of integers with no digit //repeating more than m (=2 here) times for t(=1) inputs with each input //being a arr[i] (=4) digit number. 

回答

0

不知道這是問題,但...是一個問題

看的情況下if (m<arr[i])(這是你的情況下,如果我理解正確的,因爲t是1;唯一有效的arr[i]arr[0],它是4並且大於m即2)。

您的實際代碼是

 for(int j=arr[i]-1;j>m;j++) 
      sum=sum-comb(arr[i],j)*pow(9,arr[i]-j+1); 

記住,arr[i]arr[0]是4,和m == 2,你的代碼變得

 for (int j = 3 ; j > 2 ; j++) 
      sum -= comb(4, j) * pow(9, 5 - j); 

所以從3 j開始並遞增直到j > 2;但如果j從3開始並遞增大於2即可。

我想你的代碼應該是遞減j;像

 for (auto j = arr[i] - 1 ; j > m ; ++j) 
      sum -= comb(arr[i], j) * pow(9, arr[i]-j+1); 
0

@ max66指出,爲什麼你的程序是停留在循環。

讓我解釋爲什麼矢量ARR沒有顯示我想你輸入正確讀取它的輸出4.

。但gdb尚未打印。由於輸出是緩衝的,所以它不需要在屏幕上同時打印cout。 如果你想這樣做,那麼你應該刷新輸出。

for(int i=0;i<t;i++) 
    cout<<arr[i]<<" "<<flush;