我需要在C中创建一个程序,它输出用户输入的间隔中不同数字的所有数字。这就是我想出来的。
#include<stdio.h>
int main(){
int n, m, k = 0, p, flag, last, temp;
do{
printf("Enter m and n (m < n):\n"); scanf("%d %d", &m, &n);
if (m < n) {
break;
}
else printf("\Error- m > n! Try again.\n\n");
} while (k == 0);
printf("Numbers are:\n");
for (k = m; k <= n; k++) {
p = k;
flag = 0;
if (p < 10) {
flag = 1;
}
last = (p / 10) % 10 ;
while (p > 0) {
temp = p % 10;
p = p / 10;
if (temp == last ){
flag = 1;
}
last = temp;
}
if (flag != 1) {
printf("%d ", k);
}
}
getch();
return 0;
}
示例输出:
Enter m and n (m < n):
100 130
Numbers are:
101 102 103 104 105 106 107 108 109 120 121 123 124 125 126 127 128 129 130
所以在这种情况下的问题是它输出101和121.它不应该因为它们有两个相同的数字。我该如何解决这个问题?
答案 0 :(得分:1)
我相信这是您正在寻找的解决方案。如果将数字转换为字符串,则更容易检查其数字。请注意,序列中每个数字需要两个循环。它简洁但仍然很昂贵。 (使用标志 -std = c11 编译它。)
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Enter two non-negative numbers in ascending order:\n");
int min, max;
scanf("%d %d", &min, &max);
while(min < 0 || max < 0 || min > max)
{
printf("Invalid input! Please enter two non-negative numbers in ascending order:\n");
scanf("%d %d", &min, &max);
}
printf("The numbers without repeated digits in the interval [%d, %d] are:\n", min, max);
for(int n = min; n <= max; ++n)
{
char digits[32];
sprintf(digits, "%d", n);
int repeated = 0;
for(int i = 0; digits[i] && !repeated; ++i)
{
for(int j = i + 1; digits[j]; ++j)
{
if(digits[i] == digits[j])
{
repeated = 1;
break;
}
}
}
if(!repeated) printf("%d ", n);
}
printf("\n");
return 0;
}
答案 1 :(得分:0)
最后让它发挥作用!
int main(){
int n, m, k = 0, p = 0, flag, i = 0, j, dig[10];
do{
printf("Enter m and n (m < n):\n"); scanf("%d %d", &m, &n);
if (m < n) {
break;
}
else printf("\Error- m > n! Try again.\n\n");
} while (k == 0);
printf("Numbers in the interval [%d, %d] are:\n", m, n);
for (k = m; k <= n; k++){
p = k;
flag = 0;
dig[i] = 0;
i = 0;
if (p < 10){
continue;
}
while (p > 0){
dig[i] = p % 10;
p = p / 10;
i++;
}
dig[i] = -1;
for (i = 0; dig[i] > -1; i++){
for (j = i + 1; dig[j] > -1; j++){
if (dig[i] == dig[j]){
flag = 1;
}
}
}
if (flag == 0){
printf("%d\t", k);
}
}
getch();
return 0;
}