Как сохранить введенные пользователем значения после того, как он оставит опцию «ввод», и заставить его начать с того, с чего он закончил? - PullRequest
0 голосов
/ 13 февраля 2019

У меня есть определенное упражнение, которое я должен сделать.Надеюсь, кто-то понимает, что я не смог сделать.

всякий раз, когда пользователь нажимает ввод, вводит менее 10 целых чисел, нажимает q, чтобы выйти из опции, а затем возвращается, все его входные значения исчезают.Я хочу, чтобы значения оставались там до тех пор, пока общее количество сохраненных элементов не станет равным 10. Как мне это сделать?

Примечание!Пользователь не должен выходить из приложения (которое в данном случае является CMD), скорее, он должен иметь возможность только оставить опцию «ввод» и при этом сохранить свои входные значения «сохраненными».

#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define L 10

void view(int a[])

     {
        int i;
        printf("\n Here are the currently stored values\n");  

        printf("[");
        for(i=0; i<L; i++)
            {
            printf(" %d ",a[i]);
            }
        printf("]");
     }

int enter(int a[], int n)
     {
         printf("\n Note! You can press any letter if you want to return to the main menu. \n");

         for(int i=0; i<L; i++)

            {

            int mesa;
            printf(" Enter measurement #%d (or q to quit): ", n+1);
            int check = scanf("%d",&mesa); 

            if(check)
                {
                    a[i] = mesa;
                    n++;
                }
            else
                { 
                    char temp;
                    scanf(" %c",&temp);
                    return n;
                }
            }
           return n;
     }

void compute(int a[], int n)

     {
            printf(" Computing...\n");

            //Min value
            {
                int i;
                int min = 10000;

                for (i = 0; i < L; i++)
                if(a[i] < min)
                min = a[i];

                printf("\n The min value is: %d \n", min);
            }

            //Max value
            {
                int i;
                int max = a[0];

                for (i = 0; i < L; i++) 
                if (a[i] > max) 
                max = a[i]; 

               printf(" The max value is: %d \n", max);
            }

            // Average & Normalization
            {
                float average;
                int i;
                int norm;
                int sum;

                for(i = 0; i < L; ++i)
                    {
                    sum = sum + a[i];
                    average = (float)sum / 10; //typecast - Ge en interger en tillfällig roll. På så sätt kan du säga åt programmet att du faktiskt vill ha float som svar och inte ett heltal som svar.
                    } 
                    printf(" Average value: %.2f \n", average);

                    printf(" Normalized array: [");
                for(i = 0; i < L; i++)
                    {
                    norm = a[i] - average; //average - every a[]
                    printf(" %d", (int)round(norm));
                    }
                    printf(" ]");
            }
     }

void reset(int a[])

    {
        printf(" You have chosen to reset the array. All the elements in the array will now be deleted. \n");

        //memset( a, 0, 10*sizeof(a)); <--- Kan ej användas då sizeof() funktionen läser av en variabel och inte hela arrayens storlek.
        memset( a, 0, 10*sizeof(int*));
    }

int main()

{
    char command;
    int a[L];

    printf(" Hello and welcome to this measurement tool. In this program you will be able to type in and analyze data.\n");
    printf(" In the section below, you can choose a letter v,e,c,r or q to do certain things. More information will be provided down below.\n");
    printf("\n v(View) - Displays currently stored values.");
    printf("\n e(Enter) - Allows you to store values. ");
    printf("\n c(Compute) - Displays the maxiumum, minimum, normalized and average value of those which are stored.");
    printf("\n r(Reset) - Deletes all stored values.");
    printf("\n q(Quit) - Exits the program. \n");
    printf("\n Please choose one of the commands above: ");

    do
    {
      int n = 0;
      scanf(" %c",&command);
      switch(command)
       {
            case 'v' : view(a);break;
            case 'e' : enter(a,n);break;
            case 'c' : compute(a,n);break;
            case 'r' : reset(a);break;
            default : printf("\n Please choose one of the options given.\n");break;
            case 'q' : 
                    {
                    printf(" Want to exit? Confirmation needed. Press q again to exit.");
                    scanf(" %c",&command);
                    }   
        }
            printf("\n VECRQ?: ");
    } while(command != 'q');
return 0;
}

1 Ответ

0 голосов
/ 13 февраля 2019

В main() переместите объявление n вне цикла:

int n = 0;
do
{
    ...

Обновите n при вызове enter():

n = enter(a,n);

Вenter функция, начните цикл с n:

for(int i=n; i<L; i++)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...