Неправильный расчет количества букв в минуту (PPM) с использованием секундомера в программе набора текста на C#.C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Неправильный расчет количества букв в минуту (PPM) с использованием секундомера в программе набора текста на C#.

Сообщение Anonymous »

Я работаю над программой повышения скорости набора текста на C# с использованием Windows Forms, и у меня возникли проблемы с правильным расчетом количества букв в минуту (PPM). Программа использует секундомер для измерения прошедшего времени, а расчет основан на количестве нажатий клавиш. Однако расчет PPM возвращает неверные значения.
Вот соответствующая часть кода:

Код: Выделить всё

using System.Diagnostics;
using System.Linq.Expressions;

namespace DAM_M07_UF1_PT1_Chamorro1_Alex
{
public partial class Form1 : Form
{
private string time;
private Stopwatch stopwatch;
Random generator = new Random();
int timesPressed;
public string[] panels = {
"There is already a vending machine for couples. It sounds like a joke, but there is already a vending machine for couples in some places. The idea is that, if we already have machines for so many things, why not a vending machine for couples? In a world where everything seems automated, now even relationships can arise from a vending machine for couples.",

"Confusing, doubtful, dark. Sometimes, everything feels confusing, doubtful, dark. When you don't have the answers, everything feels confusing, doubtful, dark, and you don't know where to go. In moments like these, it's normal to feel confused, doubtful, dark, because the path isn't always clear. You just have to remember that, even though it feels confusing, doubtful, dark, there is always a way out.",

"No plans, no schedules, and no phones. Sometimes you just want to live without plans, no schedules, and no phones. Escape from everything, no plans, no schedules, and no phones, to truly disconnect. It's a liberating idea: no plans, no schedules, and no phones. This way you could live each moment without worrying about the clock or the phone. No plans, no schedules, and no phones, just to be at peace.",

"Riding a bike from Norway to Portugal. Can you imagine what it would be like to ride a bike from Norway to Portugal? It would be an incredible adventure: riding a bike from Norway to Portugal, passing through so many places. The views, the villages, the people you would meet if you decided to ride a bike from Norway to Portugal. It would be an unforgettable trip, riding a bike from Norway to Portugal, with the freedom of the road.",

"Crab, jellyfish, and starfish. In the sea, you see creatures like the crab, jellyfish, and starfish. They are fascinating: crab, jellyfish, and starfish, each with its own shape and movement. You watch how the crab, jellyfish, and starfish move in their habitat. Crab, jellyfish, and starfish, forming a small world of marine life.",

"Pass programming. The goal is clear: pass programming. You know that if you put in the effort, you'll pass programming and feel the achievement. All those exercises and practices are leading you to one goal: pass programming. Even though it's hard, you remind yourself that the important thing is to pass programming, and that every step brings you closer to the goal.",

"Are we the two of us or is it just a thousand things? Sometimes I wonder if it's just the two of us or if it's a thousand things. Maybe everything is confusing, and we don't know if it's just the two of us or a thousand things in our minds. If we think about it, whether it's the two of us or just a thousand things, maybe it's an enigma we'll never solve. But in the end, what matters is whether it's the two of us or just a thousand things we can't control.",

"The early bird catches the worm. They always say: 'The early bird catches the worm.' It's a saying that repeats because the early bird catches the worm by taking advantage of the day. And even though it's sometimes hard to get up early, you remember that the early bird catches the worm. This saying inspires you, and you know that the early bird catches the worm to achieve their goals.",

"I’m going to make him an offer he can't refuse. When you want to achieve something, you say: 'I'm going to make him an offer he can't refuse.' It's the idea of making something so good that you say: I'm going to make him an offer he can't refuse. Sometimes you have to take risks and think: I'm going to make him an offer he can't refuse. Because in the end, opportunities come when someone says: I'm going to make him an offer he can't refuse.",

"Living alone is like being at a party where no one notices you. Sometimes, living alone feels like being at a party where no one notices you. You have freedom, but you might also feel that living alone is like being at a party where no one notices you.  Independence is beautiful, even though living alone feels like being at a party where no one notices you. You find a unique peace, even though living alone feels like being at a party where no one notices you."
};

public Form1()
{
InitializeComponent();
stopwatch = new Stopwatch();
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void startButton_Click(object sender, EventArgs e)
{
int selection = generator.Next(0, panels.Length);
typingTextBox.Text = panels[selection];
stopwatch.Restart();
timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan ts = stopwatch.Elapsed;
var hours = ts.Hours;
var minutes = ts.Minutes;
var seconds = ts.Seconds;
var milliseconds = ts.Milliseconds;
time = $"{hours}:{minutes}:{seconds}:{milliseconds}";
clock.Text = time;
}

private void timerButton_Click(object sender, EventArgs e)
{
resumeButton.Enabled = true;
timer1.Stop();
stopwatch.Stop();
userTextBox.Enabled = false;
}

private void resumeButton_Click(object sender, EventArgs e)
{
resumeButton.Enabled = false;
stopwatch.Start();
timer1.Start();
userTextBox.Enabled = true;
}

private void userTextBox_TextChanged(object sender, EventArgs e)
{
timesPressed++;
}

private void checkButton_Click(object sender, EventArgs e)
{
int errorCount = 0;
string text = userTextBox.Text;
string correctText = typingTextBox.Text;

// Compare each character
for (int i = 0; i < text.Length; i++)
{
if (text[i] != correctText[i])
{
errorCount++;
}
}

// If no errors, calculate letters per minute
if (errorCount == 0)
{
TimeSpan ts = stopwatch.Elapsed;
double totalSeconds = ts.TotalSeconds; // Use seconds for more accurate calculation
double lettersPerSecond = totalSeconds > 0 ? timesPressed / totalSeconds : 0;
double lettersPerMinute = lettersPerSecond * 60; // Convert to letters per minute

// Round the value
lettersPerMinute = Math.Round(lettersPerMinute, 2);

MessageBox.Show($"Letters per minute: {lettersPerMinute}");
}
else
{
MessageBox.Show($"Something is not quite right, you have {errorCount} errors.");
}
}
}
}
Проблема:
Расчет PPM кажется неверным, хотя секундомер измеряет прошедшее время. Переменная timesPressed увеличивается каждый раз, когда пользователь вводит символ, но количество букв в минуту рассчитывается путем деления количества нажатий клавиш на общее количество затраченных секунд. Результат кажется неточным, и я не уверен, в чем проблема.
Что я пробовал:
  • Я использовал Stopwatch.Elapsed, чтобы получить общее время в секундах, затем посчитал количество букв в секунду и преобразовал его в количество букв в минуту.

    Я также подумал, что событие TextChanged может срабатывать слишком часто, но я все равно получаю неточные результаты.
Вопросы:
< ol>
[*]Является ли метод «Секундомер», который я использую правильным подходом для измерения затраченного времени для расчета скорости набора текста?

[*]Как повысить точность расчета количества букв в минуту?

[*]Есть ли более эффективные способы отслеживать нажатия клавиш и затраченное время в программе повышения скорости набора текста?



Подробнее здесь: https://stackoverflow.com/questions/791 ... arp-typing
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Верен ли мой расчет количества символов в минуту в этом приложении для проверки набора текста?
    Anonymous » » в форуме C#
    0 Ответы
    14 Просмотры
    Последнее сообщение Anonymous
  • Как я могу исправить неправильный расчет среднего балла в моей Java-программе?
    Anonymous » » в форуме JAVA
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous
  • Использование секундомера в C#
    Anonymous » » в форуме C#
    0 Ответы
    12 Просмотры
    Последнее сообщение Anonymous
  • Задержка на основе секундомера несовместима на Linux-ARM по сравнению с Windows
    Anonymous » » в форуме Linux
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous
  • Вертикальная атака с серединой заглавных букв вместо строчных букв?
    Anonymous » » в форуме Html
    0 Ответы
    216 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C#»