看了第一个大佬的,感觉是我想复杂了,不过还是可以值得借鉴一下的
#include "iostream" #include "cstdio" #include "cstring" #include "string" #include "sstream" #include "cmath" using namespace std; string a[1001][1001]; int main() { int n; while (cin >> n) { if (n == 1) printf("1/1\n"); else { int m = sqrt(n); m = m + 2; for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { stringstream ii, jj; string s1, s2; ii << i + 1; ii >> s1; jj << j + 1; jj >> s2; a[i][j] = s1; a[i][j] += '/'; a[i][j] += s2; } } int temp = 1; int x = 0, y = 0; loop:if (x == 0) { y = y + 1; while (y >= 0) { if (temp == n - 1) cout << a[x][y] << endl; temp++; if (temp == n) { goto loop1; } x++; y--; } y++; x--; } if (y == 0) { x = x + 1; while (x >= 0) { if(temp==n-1) cout << a[x][y] << endl; temp++; if (temp == n) { goto loop1; } x--; y++; } x++; y--; } loop1:if (temp < n) goto loop; } } return 0; }
附上第二次写的正确的答案
#include <iostream> #include <cmath> #include <string> #include <cstdio> using namespace std; int main() { int n; while (cin >> n) { int i = 0; int s = 0; while (s < n) { i++; s = s + i; } if (i % 2 == 1) { s = s - i; int a = i; int b = 1; for (int i = 1; i < n - s; i++) { a--; b++; } cout << a << "/" << b << endl; } else { s = s - i; int a = 1; int b = i; for (int j = 1; j < n - s; j++) { a++; b--; } cout << a << "/" << b << endl; } } return 0; }
附上第三种方法=.= ,可以优化下,懒得优化了
#include <iostream> #include <cmath> #include <string> #include <cstdio> using namespace std; int main() { int n; while(cin >> n) { int a, b; if (n == 1) cout << "1/1" << endl; if (n == 2) cout << "1/2" << endl; else { a = 2; b = 1; int flag = 1; int flag1 = 1, flag2 = 1; for (int i = 3; i < n; i++) { if (b == 1 && flag == 1) { a = a + 1; flag = 0; flag1 = 0; flag2 = 1; continue; } if (a == 1 && flag == 1) { b = b + 1; flag = 0; flag2 = 0; flag1 = 1; continue; } if (!flag1) { a = a - 1; b = b + 1; flag = 1; continue; } if (!flag2) { a = a + 1; b = b - 1; flag = 1; continue; } } cout << a << "/" << b << endl; } } return 0; }
0.0分
0 人评分
C语言程序设计教程(第三版)课后习题4.9 (C语言代码)浏览:717 |
九宫重排 (C++代码)浏览:2194 |
简单的a+b (C语言代码)浏览:752 |
C语言训练-求1+2!+3!+...+N!的和 (C语言代码)万恶的long long浏览:906 |
C语言程序设计教程(第三版)课后习题1.6 (C语言代码)浏览:574 |
1009题解浏览:802 |
C语言程序设计教程(第三版)课后习题8.4 (C语言代码)浏览:541 |
The 3n + 1 problem (C语言代码)浏览:550 |
C语言程序设计教程(第三版)课后习题6.7 (C语言代码)浏览:725 |
盐水的故事 (C语言代码)浏览:1602 |