C语言while循环输入'y'确认重跑却意外终止的问题修复
循环提前终止的问题修复方案
核心故障点定位
- scanf传参错误导致非法内存访问:循环末尾的输入语句
scanf(" %c", l_res);违反了C语言scanf的传参规则:除%s格式符外,其余所有格式对应参数都必须传入变量的内存地址,才能把输入值写入变量。此处直接传入l_res的字符值作为内存地址,属于访问非法地址,轻则无法写入输入值,重则触发栈内存崩溃直接终止程序。修正方式为给l_res补充取地址符,改为scanf(" %c", &l_res); - 字符串数组容量不足引发栈越界:代码中定义的
char f_res[4]仅能容纳3个有效字符加1个字符串结束符,但用户输入的"Nano"、"Pico"字符串,加上末尾的\0分别需要5字节、6字节存储空间。scanf("%s", f_res)读入字符串时会超出数组边界写内存,直接覆盖相邻栈位置存储的l_res变量值,篡改循环判定条件。修正方式为扩容f_res数组,比如定义为char f_res[10];完全覆盖最长输入的存储需求。 - 作用域遮蔽引发的逻辑偏差:Nano单位分支内重新定义了局部
float x,将外层作用域的整型变量x完全遮蔽,后续倍率计算和输出和设计的换算逻辑不匹配,虽不直接触发循环终止,但会导致计算结果错误。
修正后的可运行代码
#include <stdio.h> #include <string.h> int main() { //VARIABLES char f_res[10]; char l_res = 'y'; int a,b,c; long long cap_value; while(l_res == 'y' || l_res == 'Y') { printf("Enter 3 digit capacitor Code: "); scanf("%d %d %d",&a,&b,&c); cap_value = a * 10 + b; printf("What is the unit of the value?(Pico-picofarad, Nano-Nanofarad): "); scanf("%s", f_res); if(strcmp(f_res, "Pico") == 0) { if(c > 0 && c <=5) { while(c > 0) { cap_value *= 10; c--; } } printf("\nCapacitor value is: %lld pF\n\n",cap_value); } else if(strcmp(f_res, "Nano") == 0) { float nano_value = (a *10 + b) * 0.001f; if(c >0 && c <=5) { while(c >0) { nano_value *= 10; c--; } } printf("\nCapacitor value is: %.3f nF\n\n",nano_value); } else { printf("\nINVALID Input!\n\n"); } printf("Do you want to enter other capacitor Code?( y-Yes, n-No): "); scanf(" %c", &l_res); } return 0; }
内容的提问来源于stack exchange,提问作者Myorix
相关产品推荐
相关产品推荐

