C语言加法程序异常:求和恒为0.00且触发Segmentation Fault(core dumped)
问题分析与修复方案
你遇到的求和结果始终为0.00以及段错误问题,都是代码里的几个细节疏漏导致的,我帮你逐个梳理并解决:
1. 触发段错误的核心原因:scanf读取字符时未传入地址
在重启选择的循环里,你写了:
scanf(" %c", restart);
scanf要求传入变量的地址来存储输入值,但你直接传了restart这个char变量的值,程序会把这个值当成内存地址去访问,这必然会触发Segmentation Fault。
修复方式:添加取地址符&:
scanf(" %c", &restart);
2. 求和结果异常的双重原因
- 格式符不匹配:
currnum是float类型,但你用了%d(整数格式符)来读取输入:
这会导致输入的数字被错误解析并存储,最终求和结果完全不符合预期。应该用scanf(" %d", &currnum);%f格式符:scanf(" %f", &currnum); - 变量未初始化:
sum变量定义时没有初始化,默认是随机的垃圾值。你看到的0.00只是巧合,实际运行中可能得到任意奇怪的结果。需要初始化sum为0:float currnum, sum = 0.0f;
3. 变量重复定义导致的逻辑混乱
你在main函数开头定义了char restart;,又在重启循环内部再次定义了char restart = 'N';。内层的restart会覆盖外层变量,导致最后判断while(restart == 'Y')时,用的是外层未初始化的restart,逻辑完全混乱。
修复方式:删除内层的重复定义,把初始化移到外层:
int main() { char restart = 'N'; // 直接在这里初始化外层变量 //Loop for restart do{ /* Starts Variables for Current number, sum, number place count, and restart choice */ float currnum, sum = 0.0f; int count = 1; // 删掉这里的 char restart = 'N'; // ... 后续代码
4. 多余的float关键字导致语法问题
你在printf前面多写了一个float:
float printf("Enter %d%s number: ", count, end);
这是语法错误,编译器会报错,直接删掉float即可:
printf("Enter %d%s number: ", count, end);
5. 重启选择的循环条件永远为真
你的循环条件是:
while(restart != 'Y' || restart != 'N' );
这个条件永远成立,因为不管restart是Y还是N,其中一个判断必然为真,会导致无限循环。应该用逻辑与&&:
while(restart != 'Y' && restart != 'N' );
6. 数字计数错误
最后输出的count值会比实际输入的数字个数多2(初始为1,输入第一个数后count+1,输入0终止时又count+1),所以应该输出count-2;另外建议避免把终止用的0计入求和,逻辑更合理。
修复后的完整代码
/*Basic addition program*/ /*May 31 2018*/ #include <stdio.h> #include <stdlib.h> #include<string.h> int main() { char restart = 'N'; // 初始化外层restart //Loop for restart do{ /* Starts Variables for Current number, sum, number place count, and restart choice */ float currnum, sum = 0.0f; // 初始化sum为0 int count = 1; //Loop for user input amount until 0 is submitted do{ //Initiates number place ending array char end[3]; printf("Basic Addition Program\nType 0 To Terminate\n\n"); //Chooses which ending to add to array if(count == 1){ strcpy(end, "st"); }else if(count == 2){ strcpy(end, "nd"); }else if(count == 3){ strcpy(end, "rd"); }else if(count > 3){ strcpy(end, "th"); } //Requests user input and adds to current number printf("Enter %d%s number: ", count, end); scanf(" %f", &currnum); // 用%f读取float类型 //Clears Screen (Unix) system("clear"); //Adds current number to overall sum,跳过终止用的0 if(currnum != 0) { sum += currnum; count++; } }while(currnum != 0); //States numbers inputted and sum printf("You added %d numbers and got a sum of %.2f\n", count-1, sum); //Do while loop for user error do{ printf("Restart?(Y/N): "); scanf(" %c", &restart); // 传入变量地址 //Tests if numbers have been inputted in lowercase and corrects accordingly if(restart == 'y'){ restart = 'Y'; }else if(restart == 'n'){ restart = 'N'; } }while(restart != 'Y' && restart != 'N' ); // 修正循环条件 }while(restart == 'Y'); return 0; }
内容的提问来源于stack exchange,提问作者C蜐汀e廷谭pt獭虝i檀蜆谈u蜏蜖蜐m
相关产品推荐
相关产品推荐

