理清邏輯,用for迴圈列印
阿新 • • 發佈:2018-12-13
(1)編寫程式數一下0-100之間9的個數:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int cnt = 0;
for (int i = 0; i <= 100; ++i)
{
if (i % 10 == 9)//取個位
{
++cnt;
}
if (i / 10 % 10 == 9)//取十位
{
++cnt;
}
}
printf("%d\n", cnt);
system("pause");
return 0;
}
( 2)計算1/1-1/2+1/3-1/4+…+1/99-1/100
#include<stdio.h>
#include<stdlib.h>
int main()
{
double sum = 0;
for (int i = 1; i <= 100; i=i+2)//求i等於奇數時的和,
{
sum = sum + 1.0 / i;
}
for (int i = 2; i <= 100; i = i + 2)//求i等於偶數時的和,
{
sum = sum - 1.0 / i;
}
printf("%lf\n", sum);
system("pause");
return 0;
}
(3)將兩個陣列中的數字交換:(陣列中元素個數相等)
#include<stdio.h> #include<stdlib.h> int main() { int a[] = { 1, 2, 3, 4 }; int b[] = { 5, 6, 7, 8 }; int tmp = 0; for (int i = 0; i < sizeof(a) / sizeof(a[0]); ++i)//遍歷一下陣列,建立臨時變數交換a[i],b[i]的值, { tmp = a[i]; a[i] = b[i]; b[i] = tmp; } for (int i = 0; i < sizeof(a) / sizeof(a[0]); ++i)//迴圈列印陣列a的值 { printf("%d ", a[i]); } printf("\n"); for (int i = 0; i < sizeof(b) / sizeof(b[0]); ++i)//迴圈列印陣列b的值, { printf("%d ", b[i]); } printf("\n"); system("pause"); return 0; }
(4)列印菱形
#include<stdio.h>
#include<stdlib.h>
void PrintfLine(char g_blank, char g_start)
{
for (int i = 1; i <= g_blank; ++i)
{
printf(" ");
}
for (int i = 1; i <= g_start; ++i)
{
printf("*");
}
printf("\n");
}
void PrintfLingxing(int n)
{
for (int i = 1; i < n; ++i)
{
PrintfLine(n - i, 2 * i - 1);
}
PrintfLine(0, 2 * n - 1);
for (int i = n - 1; i > 0; --i)
{
PrintfLine(n - i, 2 * i - 1);
}
}
int main()
{
PrintfLingxing(10);
system("pause");
return 0;
}