当我运行这段代码时,我收到一条警告:控件到达非无效函数 [Wreturn-type] 的末尾。我认为这可能是一个无限递归的情况,但我不知道如何解决它。
在您输入非数字的内容之前,该程序应该会接收数字。 poramnet()
函数将任何 9 与 7 交换并返回它们。我还有一个条件,我必须打印出最大的 5 个数字,如果数组中没有 5 个数字,我必须将它们全部打印出来。
#include <stdio.h>
#include<string.h>
#include<malloc.h>
#include<ctype.h>
int poramnet(int n, int m, int i){ //i should start with 1
if(n==0)
return m;
if(n%10==9){
m+=i*7;
}
else{
m+=i*(n%10);
return poramnet(n/10, m, i*10);
}
}
int main()
{
int array1[100], i=0, output[100], br=1, j, temp, m=0, n;
while(1){
scanf("%d", &array1[i]);
if(!isdigit(array1[i]))
break;
i++;
}
n=i;
for(i=0;i<n;i++){
output[i]=poramnet(array1[i], m, br);
}
for(i=0;i<n-1;i++){
for(j=1;i<n;j++){
if(output[i]>output[j]){
temp=output[i];
output[i]=output[j];
output[j]=temp;
}
}
}
if(n<5){
for(i=0;i<n;i++)
printf("%d ", output[i]);
}
else{
for(i=0;i<5;i++){
printf("%d ", output[i]);
}
}
return 0;
}
最佳答案
注意事项:
- 始终使用括号
if
阻止,即使您认为没有必要。 - 替换了
scanf
与getc
.- 这里必须忽略“ENTER”键,
- 然后转换为
int
, - 然后用
isdigit
检查.
- 您的一个嵌套 for 循环有一个错误:
j<n
是需要的,不是i<n
. - 将函数的退出/返回次数保持在最低限度。如果您仍然想从一个函数中使用多个返回值,那么至少要设置一个默认返回值,您知道它总是会被命中,即使您的程序出现错误也是如此。
查看代码中的注释以获取更多详细信息。
main.cpp
#include <stdio.h>
#include<string.h>
#include<malloc.h>
#include<ctype.h>
int poramnet(int n, int m, int i){ //i should start with 1
// Always put brackets with if !!! It avoid confusion
if(n==0) {
return m;
}
if(n%10==9){
m+=i*7;
return m;
}
else{
m+=i*(n%10);
return poramnet(n/10, m, i*10);
}
// put a default return always, so you know if the function returns
// in an expected way, that you can track it back down.
return -1;
}
int main()
{
int array1[100], i=0, output[100], br=1, j, temp, m=0, n;
// Instead of scanf, you could use getc, ignore the "enter" key-press,
// and convert to an int from char and then check with isdigit().
while(1){
char tempChar;
tempChar = getc(stdin);
if (tempChar != '\n') {
// printf("what you entered is, %c\n", tempChar);
// printf("is it a digit: %d\n", !isdigit(tempChar));
tempChar = tempChar - '0';
// printf("is it a digit: %d\n", !isdigit(array1[i]));
if(isdigit(tempChar)) {
break;
}
array1[i] = tempChar;
i++;
}
}
n=i;
for(i=0;i<n;i++){
output[i]=poramnet(array1[i], m, br);
}
for(i=0;i<n-1;i++){
for(j=1;j<n;j++){ // you had a bug here also! you need j<n and not i<n !! copy-paste error!
if(output[i]>output[j]){
temp=output[i];
output[i]=output[j];
output[j]=temp;
}
}
}
if(n<5){
for(i=0;i<n;i++)
printf("%d ", output[i]);
}
else{
for(i=0;i<5;i++){
printf("%d ", output[i]);
}
}
return 0;
}
输出
junglefox@ubuntu:~/test_programs$./test
1
2
3
4
5
a
1 4 3 2 5 junglefox@ubuntu:~/test_programs$
关于c - 程序挂起,不输出任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54178306/