本文目錄一覽:
c語言!對角線
25
左右兩條對角線和
是說兩個對角線上所有元素的和
中間的5 被使用了兩次。
用符號「□」「■」C語言畫出正方形和正方形對角線
// Eclipse C++ 和 Code::Block 調試通過
// 提供控制台簡易菜單 以及 正方形 和 長方形 輸出。
// 長方形 對角線 輸出不穩定 (幾何方程離散化需要更複雜的演算法,故為深入)長寬較大時可以用
// 邊長大約32 窗口無法顯示完整
#include iostream
#include stdlib.h
#include stdio.h
#include conio.h
using namespace std;
// func declaration—————————————–
void set_prefix_str(char* str, int len, char ch);
void println_str(const char* str);
void print_pix(const char* str);
int print_rectangle(float rectX,float rectY);
// gloabl ————————————————–
const char* PIX0 = “□”;
const char* PIX1 = “■”;
int LEN = 8;
char* PREFIX = NULL;
// main menu ———————————————–
int main()
{
float rectX;
float rectY;
int option = -1;
set_prefix_str( PREFIX, LEN, ‘ ‘ );
while(1) {
system(“cls”);
println_str(“”);
println_str(“”);
println_str(” Print Rectangle”);
println_str(“”);
println_str(“”);
println_str(“[1] Print 正方形”);
println_str(“[2] Print 長方形(不穩定)”);
println_str(“[3] setting”);
println_str(“”);
println_str(“[0] Exit”);
println_str(“”);
option = getch();
println_str(“”);
if ( option ‘0’ or option ‘3’ ) {
continue;
}
if (‘0’==option) {
break;
}
if (‘3’==option) {
print_pix(“設置左側縮進: “);
cinLEN;
set_prefix_str( PREFIX, LEN, ‘ ‘ );
continue;
}
if (‘1’==option) {
print_pix(“正方形邊長: “);
cinrectY; rectX=rectY;
println_str(“”);
}
if (‘2’==option) {
print_pix(“矩形長: “);
cinrectX;
println_str(“”);
print_pix(“矩形高: “);
cinrectY;
println_str(“”);
}
if (rectX0 or rectX64) {
println_str(“X參數範圍錯誤”);
system(“pause”);
continue;
}
if (rectY0 or rectY64) {
println_str(“Y參數範圍錯誤”);
system(“pause”);
continue;
}
system(“cls”);
println_str(“”);
print_rectangle(rectX,rectY);
println_str(“”);
system(“pause”);
continue;
}
return 0;
}
// tools —————————————————
void println_str(const char* str) {
cout str endl PREFIX; // or use printf to print
}
void print_str(const char* str) {
cout str PREFIX; // or use printf to print
}
void print_pix(const char* str) {
cout str; // or use printf to print
}
void set_prefix_str(char* str, int len, char ch) {
if ( str ) {
free(str);
}
//use new or malloc
str = (char*) malloc( sizeof(char)*(len+1) );
//new char[](len+1)
//delete[](str)
for (int i = 0; i len; ++i) {
str[i] = ch;
}
str[len] = ‘\0’;
}
int print_rectangle(float rectX, float rectY) {
int maxX = (int)(rectX);
int maxY = (int)(rectY);
//對角線方程 y = kx + b
//正方形則 k = +/-1
float k1 = maxY/(float)(maxX);
float k2 = -maxY/(float)(maxX);
int count = 0;
for (int y = 0; y = maxY; ++y) {
for (int x = 0; x = maxX; ++x) {
//橫邊方程
if (0==y or maxY==y) {
print_pix(PIX1);
++count;
continue;
}
//縱邊方程
if (0==x or maxX==x) {
print_pix(PIX1);
++count;
continue;
}
//對角線方程 y = kx + b
if ((int)(k1*x)==y or (int)(k2*x)+maxY==y) {
print_pix(PIX1);
++count;
continue;
}
print_pix(PIX0);
++count;
continue;
}
println_str(“”);
}
return count;
}
c語言對角線
從左上角到右下角的對角線叫右下對角線,也叫主對角線。
從右上角到左下角的對角線叫左下對角線,也叫副對角線。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/257166.html