Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

KristianZanev avatar KristianZanev 16 Точки

Проблем с 02. Exam Preparation While-Loop - Exercise

Здравейте, моля за малко помощ с тази задача. Все още while-loop задачите са ми тъмна индия. Благодаря! Линк към задачката ⦁    Подготовка за изпит

function exam(input) {
    let inputOfbadGrades = Number(input.shift());

    let countForBadGrades=0;
    let sumGrades =0;
    let counterForGrades=0;
    let lastProblem='';

    while (countForBadGrades < inputOfbadGrades) {
        let nameOfExercise=input.shift();
        let grade=Number(input.shift());

        if (nameOfExercise=='Enough'){
            sumGrades = sumGrades/counterForGrades;
            console.log(`Average score: ${sumGrades}\nNumber of problems: ${counterForGrades}\nLast problem: ${lastProblem}`);
        
        }
        if (grade <= 4){
            countForBadGrades++
            lastProblem=nameOfExercise;
        }
        counterForGrades++
        sumGrades++
    }
    if(counterForGrades==inputOfbadGrades){
        console.log(`You need a break, ${countForBadGrades} poor grades.`);
        
    }
}
exam ([3,
    'Money',
    6,
    'Story',
    4,
    'Spring Time',
    5,
    'Bus',
    6,
    'Enough'])

 

Тагове:
0
Programming Basics 06/02/2019 22:12:22
Tspetrova avatar Tspetrova 125 Точки
Best Answer

Ето и моето решение на Java :-)  Успех!

https://pastebin.com/9aEjt6VZ

0
KristianZanev avatar KristianZanev 16 Точки

Така проработи благодаря!

0
chrisi2712 avatar chrisi2712 272 Точки

Здравейте, моето решение е нa C#, но логиката и последователносста на  проверките е същата.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExamPreparation
{
    class Program
    {
        static void Main(string[] args)
        {
            int badGrades = int.Parse(Console.ReadLine());
            string nameTask = Console.ReadLine();
            int counterBadGrades = 0;
            int sumGrades = 0;
            int counterTasks = 0;
            string lastTask = "";
            bool isTheGradeBad = false;

            while(nameTask!= "Enough")
            {
                int grade = int.Parse(Console.ReadLine());
                sumGrades += grade;
                counterTasks++;

                if (grade<=4)
                {
                    counterBadGrades++;
                    
                    if (counterBadGrades==badGrades)
                    {
                        Console.WriteLine($"You need a break, {counterBadGrades} poor grades.");
                        isTheGradeBad = true;
                        break;
                    }
                }

                lastTask = nameTask;
                nameTask = Console.ReadLine();
            }


            if (isTheGradeBad==false)
            {
                double average = sumGrades * 1.0 / counterTasks;
                Console.WriteLine($"Average score: {average:F2}");
                Console.WriteLine($"Number of problems: {counterTasks}");
                Console.WriteLine($"Last problem: {lastTask}");
            }
            
        }
    }
}

0
KristianZanev avatar KristianZanev 16 Точки

Така проработи благодаря!

0
geotradepopov avatar geotradepopov 1 Точки

Ей, благодаря за споделеното решение! Няколко часа се чудих къде ми е грешката! laugh string nameTask = Console.ReadLine();  преди while, оправя всичко. В насоките не беше описано така.

0
Hursa avatar Hursa 2 Точки

Ако първата задача е Enough се получва делене на нула. 

0
Stoyan.Ivanov.87 avatar Stoyan.Ivanov.87 20 Точки

Това е моето решение :)

 

 

function examPreparation(input) {

let negativeGradesLimit = Number(input.shift());

 

let countOfBadGrades = 0;

let sumGrades = 0;

let gradesCounter = 0;

let lastProblem;

let avgGrade;

 

while (countOfBadGrades < negativeGradesLimit) {

let nameofExercise = input.shift();

let grade = Number(input.shift());

if (nameofExercise == "Enough") {

avgGrade = sumGrades / gradesCounter;

console.log(`Average score: ${avgGrade.toFixed(2)}`);

console.log(`Number of problems: ${gradesCounter}`);

console.log(`Last problem: ${lastProblem}`);

break;

}

if (grade <= 4) {

countOfBadGrades++;

}

sumGrades += grade;

gradesCounter++;

lastProblem = nameofExercise;

}

 

if (countOfBadGrades == negativeGradesLimit) {

console.log(`You need a break, ${countOfBadGrades} poor grades.`)

}

}

0
AlexMarinov87 avatar AlexMarinov87 15 Точки

ето го и моето решение:

function examPreparation(input) {
    let badGradesAllowed = Number(input.shift());
    let badGradesCounter = 0;
    let goodGradesCounter = 0;
    let gradesSum = 0;
    let lastProblem = "";
    let nameOfExcercise;
    let grade = 0


    while (badGradesCounter < badGradesAllowed) {
        nameOfExcercise = input.shift();
        grade = Number(input.shift());

        if (nameOfExcercise == "Enough") {
            let totalCounter = badGradesCounter + goodGradesCounter;
            let averageScore = gradesSum / totalCounter;
            console.log(`Average score: ${averageScore.toFixed(2)}`);
            console.log(`Number of problems: ${totalCounter}`);
            console.log(`Last problem: ${lastProblem} `);
            break;
        }
        if (grade <= 4) {
            badGradesCounter++;
        } else {
            goodGradesCounter++;
        }
        lastProblem = nameOfExcercise;
        gradesSum += grade;
    } if (badGradesCounter == badGradesAllowed) {
        console.log(`You need a break, ${badGradesCounter} poor grades.`)
    }
}

0
Hursa avatar Hursa 2 Точки

Какво се случва когато първата задача е Enough?

делене на нула 

 

0
Hursa avatar Hursa 2 Точки

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExamPrep
{
    class Program
    {
        static void Main(string[] args)
        {
            int a= int.Parse(Console.ReadLine());
            string lastproblem="a";
            double count = 0;
            double pcount = 0;
            double SM = 0;
            int evalution = 1;
            while (true)
            {
                string problem = Console.ReadLine();
                 if (problem == "Enough")
                    {if (count !=0)
                    { 
                    Console.WriteLine($"Average score: {(SM ) / count:F2}");
                    Console.WriteLine(("Number of problems: ")+count);
                    Console.WriteLine(("Last problem: ")+lastproblem);
                    break;}
                    else {

                        int count1 = 1;
                        Console.WriteLine(("Average score: ")+(SM) / count1);
                        Console.WriteLine(("Number of problems: ")+count);
                        Console.WriteLine(("Last problem: ")+"not");
                    }
                }

                 else
                { evalution = int.Parse(Console.ReadLine());
                  

                    if (evalution < 5)
                    {
                        pcount++;

                        if (pcount == a)
                        {
                            Console.WriteLine("You need a break, "+a + " poor grades.");
                            break;
                        }
                    }
                }
                  lastproblem = problem;
                SM +=  evalution;
                 count++;


            }


        }
    }
}
 

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.