2013-10-10 42 views
2
#include<iostream> 
#include<conio.h> 
#include<math.h> 
#include<vector> 
#include<iterator> 
#include<string> 
using namespace std; 

int main() { 
    int k=0; 
    string s; 

    cout<<"string "; 

    getline(cin,s);    //taking in a string from the user 

    float n=s.size();   //storing size of string 

    int f=floor((sqrt(n))); //floor of square root of input string 

    int c=ceil((sqrt(n))); //ceiling 

    int m=f*c;    //storing product of f and c 

    vector< vector<string> > vec(n<=m?f:++f, vector<string>(c)); //makes a 2d vector 
                    //depending on user's 
                    //string length 


    for(int i=0;n<=m?i<f:i<++f;i++)  //looping acc to user's input and assigning 
    { 
     for(int j=0;j<c;j++)   //string to a matrix 
     { 
      if(k<s.size()) 
      { 
       vec[i][j]=s[k]; 
       k++; 
      } 
     } 
    } 



    for(int j=0;j<c;j++)  //printing the vector 
     { 

    { 
     for(int i=0;n<=m?i<f:i<++f;i++) 

      cout<<vec[i][j]; 

    }cout<<" "; 
     } 

getch();   

} 

它不工作为N> M作为用于长度为8个字符的字符串它使2 * 3从而不能括在基体中的整个字符串的矢量和这就是为什么我使用三元以便在遇到像这样的情况时制作更大尺寸的矢量。 。那么我做错了什么?基本模糊处理程序

我只会写出整个问题。

One classic method for composing secret messages is called a square code. The spaces are removed from the english text and the characters are written into a square (or rectangle). The width and height of the rectangle have the constraint, 

    floor(sqrt(word)) <= width, height <= ceil(sqrt(word)) 

    The coded message is obtained by reading down the columns going left to right. For example, the message above is coded as: 

    imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau 


    Sample Input: 

    chillout 

    Sample Output: 

    clu hlt io 
+3

你可以a)很好地格式化代码,b)解释算法的原理思想。猜测出代码是耗时的(即使工作不正常,但) – dornhege

+1

这段代码是不可读的Phylulu mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn –

+1

为Cthulu参考+1。 ;) – abelenky

回答

2

这不会解决您的整个问题,但我仍然认为这很重要。你似乎误解了三元论的运作方式。让我们来观察它的用途在这里的一个:

for (int i = 0; n <= m ? i < f : i < ++f; i++) {} 
//    ^^^^^^^^^^^^^^^^^^^^^^^^ <--- not the intended outcome 

这不会起作用,因为三元的返回侧不“大棒”本身的地方。换句话说,i < fi < ++f都不会直接放在for循环中。相反,它会给你一个

要明白它的真正作用,首先需要明白三元是另一种做if-else的方法。上述三元,投入的if-else形式,看起来是这样的:

if (n <= m) 
    i < f; // left side of the ":" 
else 
    i < ++f; // right side of the ":" 

让我们进一步把它分解:

i < f 

这是做低于的if比较。因此,根据个人价值观,您将收到0(假)或1(真)。

所以,在你的for循环,这将发生:

for (int i = 0; 1; i++) {} 
//   ^<--- if comparison returns true 

for (int i = 0; 0; i++) {} 
//   ^<--- if comparison returns false 

所以,你的榜样,你需要循环之前找到f值。你可以使用三元的那部分,但只有当你明白它。否则,请使用其他方法查找f(预定数值)。一旦找到它,然后你可以把i < f放入for-loop。

+0

你如何评论代码?我上面的评论很难理解“现在”。 – Angersmash

+0

@Ratul:在文本之间加一个反引号(')。 – Jamal

+0

我在循环之前已将值存储在'f'中,例如让字符串长度为8.因此f将存储'(floor(sqrt(8)))'即'2'和'c = 3 '和'm = 2 * 3',即'6'。现在将大小赋值给vector。vector中的三元将检查是否(8 <= 6)'(row = 2)else row = ++ f ie 3)'然后for循环将根据创建的向量工作,也就是'i <2'(如果为true)或'i <3'(如果为false) – Angersmash