我是C初学者,这是迄今为止我最大的计划。它结合了do while循环来重新启动程序,允许用户添加任意数量的数字,并确保提交正确的字母是或否。很简单。事实是,我输入的每个数字加起来都是0.00,并且程序会给我一个分段错误(核心转储)错误,无论我选择重启。
错误:
我很清楚这可能是我忽略的一些愚蠢的细节,但请耐心等待!非常感谢帮助。
代码:
/*Basic addition program*/
/*May 31 2018*/
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char restart;
//Loop for restart
do{
/*
Starts Variables for Current number, sum,
number place count, and restart choice
*/
float currnum, sum;
int count = 1;
char restart = 'N';
//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 float
printf("Enter %d%s number: ", count, end);
scanf(" %d", &currnum);
//Clears Screen (Unix)
system("clear");
//Adds current number to overall sum
sum += currnum;
//Increases number count so that places shift by 1 (e.g 1st to 2nd)
count++;
}while(currnum != 0);
//States numbers inputted and sum
printf("You added %d numbers and got a sum of %.2f\n", count, sum);
//Do while loop for user error
do{
printf("Restart?(Y/N): ");
scanf(" %c", restart);
//Tests if numbers have ben 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;
}
答案 0 :(得分:3)
其中一个有问题的陈述是
scanf(" %c", restart); /* you need to provide the &(address) to store */
应该是
scanf(" %c", &restart);
你应该阅读编译器警告&amp;解决你自己用-Wall
标志编译。
也在声明
之下scanf("%d", &currnum); /* currnum is declared as float variable, use %f */
在下面的代码块中
char restart;
do {
/* some code */
}while(restart == 'Y');
restart
未初始化,您的编译器可能会警告您
错误:在此函数中未初始化使用'restart' [-Werror =未初始化]
所以在第一次初始化时restart
喜欢
char restart = 'Y';
最后如果你想要正确学习C,请将所有警告视为错误&amp;然后开始解决问题。例如编译如下
gcc -Wall -pedantic -Wstrict-prototypes -Werror test.c