c - 程序挂起并且不输出任何内容
问题描述
当我运行此代码时,我收到警告:控制到达非 void 函数 [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
. - 将函数的退出/返回保持在最低限度。如果你仍然想从一个函数中使用多个返回,那么至少放一个默认返回,你知道它总是会被命中,即使你编程错误。
有关详细信息,请参阅代码中的注释。
主文件
#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;
}
输出
丛林狐@ubuntu:~/test_programs$./test
1
2
3
4
5
一个
1 4 3 2 5 丛林狐@ubuntu:~/test_programs$
推荐阅读
- sql - SQL 未知 10 描述脚本
- swiftui - SwiftUI 在动画期间改变列表导致不正确的显示状态
- javascript - 如何忽略以前的 AJAX 数据返回?
- r - 在 R 中改变 case_when 日期时间数据
- javascript - 如何让 JS 选项卡选择器不滚动
- blazor - 在 Blazor WASM 启动时加载初始数据的最佳位置在哪里
- r - 如何使用 R 中的循环结构创建像 55555,4444,333,22,1 这样的模式
- java - 奇怪的 Framing.delimiter 行为
- c# - 如何从不同的会话中获取 Windows 环境变量的当前值
- r - Scrape Ebay 使用 Rvest 出售商品