【发布时间】:2019-11-08 16:49:54
【问题描述】:
我需要创建一个使用数组的函数和一个显示:
输入的所有数字的总和、输入的数字的平均值以及输入的所有数字。它将允许用户输入多达 1000 个数字。
我的大部分代码都能正常工作,我只需要弄清楚如何显示用户迄今为止输入的所有数字。有人能帮我解决这个问题吗?谢谢!
我已尝试显示输入的数字,但这不符合分配要求。
这是我到目前为止的代码:
/*
Title: Array Intro
Author: James Henderson
Desc: a program designed to display the sume, average, and all previous numbers entered of user input numbers
Date: 11/06/19
*/
#include <stdio.h>
#include <math.h>
//Create Variables
//used for math
int counter = 0;
float number, sum = 0.0, average;
//user input number
int userInt;
int userInput[1000];
//Void Function
static void sumFunction(userInput)
{
printf("\n\tWelcome!\n");
printf("Enter 1 to begin:\n");
scanf("%i", &userInput);
//switch statement
while (1)
{
switch (userInput)
{
case 1:
printf("\nEnter a number:\n");
while (1)
{
scanf("%i", &userInput);
//determine sum
number = userInput;
sum += number;
counter++;
average = sum / counter;
printf("\n The average of the numbers is %.2f", average);
printf("\n The sum of the numbers is %.2lf", sum);
printf("\n You may enter up to 1000 numbers");
printf("\n You have entered %d numbers\n", counter);
if (counter == 1000)
{
printf("\nThank you for using my program! Have a lovely day :)");
return;
}
}
}
}
}
【问题讨论】:
-
您正在使用
userInput,就好像它是单个int,但它是一个数组。您应该将数字读入userInput[counter]。你的函数内部有一个太多的while(1)层,而main中还有一个额外的层。如果给定的第一个数字不是1,则由于switch,您有一个无限循环。你应该摆脱最初的Enter 1 to begin。没有理由将userInput传递给函数(它是全局的),并且您在函数参数声明中缺少它的类型(即void sumFunction(userInput)与void sumFunction(int* userInput)。 -
您没有检查来自
scanf的错误。我知道这看起来像一个很大的列表,但早点学习这些东西是件好事,而且大部分应该很容易解决。只要确保您了解为什么应该做出改变。 -
为什么要使用全局变量?你为什么使用静态
标签: c user-input