找到数组中的回文数量
我所做的是首先找出数字的位数,然后将第一个余数乘以数字第1项,然后将剩余的2乘以数字第2项,依此类推。如果sum == num
然后它增加1运行。
#include <stdio.h>
#include <math.h>
int main() {
int a[30], i, n, cont = 0, j, rem, run = 0, sum = 0, b[300], c[300];
printf("Enter the number of elements\n");
scanf("%d", &n);
printf("Enter the array elements\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++) {
c[i] = a[i];
b[i] = a[i];
cont = 0;
while (b[i] != 0) {
b[i] = b[i] / 10;
cont++;
}
sum = 0;
while (a[i] != 0) {
rem = a[i] % 10;
sum = sum + rem * pow(10, cont - 1);
cont--;
a[i] = a[i] / 10;
}
if (sum == c[i])
run++;
}
printf("%d\n", run);
}
for
和while
循环有什么问题吗?
你的程序有效,但可以做几个评论
一份提案 :
#include<stdio.h>
#include<math.h>
#define N 30
int main()
{
int a[N],i,n,run=0;
printf("Enter the number of elements\n");
if ((scanf("%d",&n) != 1) || (n < 1) || (n > N)) {
puts("invalid number of element");
return -1;
}
printf("Enter the array elements\n");
for(i=0;i<n;i++)
{
if (scanf("%d",&a[i]) != 1)
{
puts("invalid number");
i -= 1;
continue;
}
}
for(i=0;i<n;i++)
{
int b = a[i];
int cont=0;
while(b!=0)
{
b=b/10;
cont++;
}
int sum=0;
b = a[i];
while(b!=0)
{
int rem=b%10;
sum=sum+rem*pow(10,cont-1);
cont--;
b /= 10;
}
if(sum==a[i]) {
printf("%d is a palindrome\n", a[i]);
run++;
}
}
printf("%d\n",run);
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra p.c -lm
pi@raspberrypi:/tmp $ ./a.out
Enter the number of elements
3
Enter the array elements
1
12
12321
1 is a palindrome
12321 is a palindrome
2
请注意,您还可以将字符串读取为更一般的数字并避免使用微积分