Ошибки калькулятора windows

Время на прочтение
11 мин

Количество просмотров 89K

На днях компания Microsoft открыла исходный код калькулятора. Это приложение входило во все версии операционной системы Windows. Исходный код разных проектов Microsoft достаточно часто открывался за последние годы, но новость о калькуляторе в первый же день просочилась даже в нетехнологические средства массовой информации. Что ж, это популярная, но очень маленькая программа на языке C++. Тем не менее, статический анализ кода с помощью PVS-Studio выявил подозрительные места в проекте.

Введение

Калькулятор Windows наверняка знаком каждому пользователю этой операционной системы и не требует особого представления. Теперь же любой пользователь может изучить исходный код калькулятора на GitHub и предложить свои улучшения.

Общественность, например, уже обратила внимание на такую функцию:

void TraceLogger::LogInvalidInputPasted(....)
{
  if (!GetTraceLoggingProviderEnabled()) return;
  LoggingFields fields{};
  fields.AddString(L"Mode", NavCategory::GetFriendlyName(mode)->Data());
  fields.AddString(L"Reason", reason);
  fields.AddString(L"PastedExpression", pastedExpression);
  fields.AddString(L"ProgrammerNumberBase", GetProgrammerType(...).c_str());
  fields.AddString(L"BitLengthType", GetProgrammerType(bitLengthType).c_str());
  LogTelemetryEvent(EVENT_NAME_INVALID_INPUT_PASTED, fields);
}

которая логирует текст из буфера обмена и, возможно, отправляет его на серверы Microsoft. Но эта заметка не об этом. Хотя подозрительных примеров кода будет много.

Мы проверили исходный код калькулятора с помощью статического анализатора PVS-Studio. Так как код написан на нестандартном C++, многие постоянные читатели блога анализатора усомнились в возможности анализа, но это оказалось возможным. C++/CLI и C++/CX поддерживаются анализатором. Некоторые диагностики выдали ложные предупреждения из-за этого, но ничего критичного не произошло, что помешало бы воспользоваться этим инструментом.

Возможно, вы пропустили новости и о других возможностях PVS-Studio, поэтому хочу напомнить, что кроме проектов на языках C и C++, можно проанализировать код и на языках C# и Java.

Про неправильное сравнение строк

V547 Expression ‘m_resolvedName == L«en-US»’ is always false. To compare strings you should use wcscmp() function. Calculator LocalizationSettings.h 180

wchar_t m_resolvedName[LOCALE_NAME_MAX_LENGTH];

Platform::String^ GetEnglishValueFromLocalizedDigits(....) const
{
  if (m_resolvedName == L"en-US")
  {
    return ref new Platform::String(localizedString.c_str());
  }
  ....
}

Я просматриваю отчёты анализатора, сортируя их по возрастанию номеров диагностик, и предупреждение на этот код было самым первым в списке, и очень удачным.

Дело в том, что здесь неправильно сравниваются строки. Получилось сравнение указателей вместо значений строк. Сравнивается адрес массива символов с адресом строкового литерала. Указатели всегда неравны, поэтому условие всегда ложно. Для правильного сравнения строк следует использовать, например, функцию wcscmp.

Кстати, пока я пишу эту статью, в заголовочном файле массив символов m_resolvedName превратился в полноценную строку типа std::wstring. И теперь сравнение работает правильно. К моменту, когда вы будете читать эту статью, скорее всего, многие другие ошибки тоже будут исправлены благодаря энтузиастам и таким исследованиям, как это.

Утечка памяти в нативном коде

V773 The function was exited without releasing the ‘temp’ pointer. A memory leak is possible. CalcViewModel StandardCalculatorViewModel.cpp 529

void StandardCalculatorViewModel::HandleUpdatedOperandData(Command cmdenum)
{
  ....
  wchar_t* temp = new wchar_t[100];
  ....
  if (commandIndex == 0)
  {
    delete [] temp;
    return;
  }
  ....
  length = m_selectedExpressionLastData->Length() + 1;
  if (length > 50)
  {
    return;
  }
  ....
  String^ updatedData = ref new String(temp);
  UpdateOperand(m_tokenPosition, updatedData);
  displayExpressionToken->Token = updatedData;
  IsOperandUpdatedUsingViewModel = true;
  displayExpressionToken->CommandIndex = commandIndex;
}

Мы видим указатель temp, ссылающийся на массив из 100 элементов, под который выделена динамическая память. К сожалению, память освобождается всего в одном месте функции, во всех остальных местах возникает утечка памяти. Она не очень большая, но это всё равно ошибка для C++ кода.

Неуловимое исключение

V702 Classes should always be derived from std::exception (and alike) as ‘public’ (no keyword was specified, so compiler defaults it to ‘private’). CalcManager CalcException.h 4

class CalcException : std::exception
{
public:
  CalcException(HRESULT hr)
  {
    m_hr = hr;
  }
  HRESULT GetException()
  {
    return m_hr;
  }
private:
  HRESULT m_hr;
};

Анализатор обнаружил класс, унаследованный от класса std::exception через модификатор private (модификатор по умолчанию, если ничего не указано). Проблема такого кода заключается в том, что при попытке поймать общее исключение std::exception исключение типа CalcException будет пропущено. Такое поведение возникает потому, что приватное наследование исключает неявное преобразование типов.

Пропущенный день

V719 The switch statement does not cover all values of the ‘DateUnit’ enum: Day. CalcViewModel DateCalculator.cpp 279

public enum class _Enum_is_bitflag_ DateUnit
{
  Year = 0x01,
  Month = 0x02,
  Week = 0x04,
  Day = 0x08
};

Windows::Globalization::Calendar^ m_calendar;

DateTime
DateCalculationEngine::AdjustCalendarDate(Windows::Foundation::DateTime date,
                                          DateUnit dateUnit, int difference)
{
  m_calendar→SetDateTime(date);

  switch (dateUnit)
  {
    case DateUnit::Year:
    {
      ....
      m_calendar->AddYears(difference);
      m_calendar->ChangeCalendarSystem(currentCalendarSystem);
      break;
    }
    case DateUnit::Month:
      m_calendar->AddMonths(difference);
      break;
    case DateUnit::Week:
      m_calendar->AddWeeks(difference);
      break;
  }

  return m_calendar->GetDateTime();
}

Подозрительно, что в switch не рассмотрен случай с DateUnit::Day. Из-за этого в календарь (переменная m_calendar) не добавляется значение, связанное с днём, хотя метод AddDays у календаря присутствует.

Ещё несколько подозрительных мест с другим перечислением:

  • V719 The switch statement does not cover all values of the ‘eANGLE_TYPE’ enum: ANGLE_RAD. CalcManager trans.cpp 109
  • V719 The switch statement does not cover all values of the ‘eANGLE_TYPE’ enum: ANGLE_RAD. CalcManager trans.cpp 204
  • V719 The switch statement does not cover all values of the ‘eANGLE_TYPE’ enum: ANGLE_RAD. CalcManager trans.cpp 276

Подозрительные сравнение вещественных чисел

V550 An odd precise comparison: ratio == threshold. It’s probably better to use a comparison with defined precision: fabs(A — B) < Epsilon. Calculator AspectRatioTrigger.cpp 80

void AspectRatioTrigger::UpdateIsActive(Size sourceSize)
{
  double numerator, denominator;
  ....
  bool isActive = false;
  if (denominator > 0)
  {
    double ratio = numerator / denominator;
    double threshold = abs(Threshold);

    isActive = ((ratio > threshold) || (ActiveIfEqual && (ratio == threshold)));
  }

  SetActive(isActive);
}

Анализатор указал на подозрительное выражение ratio == threshold. Эти переменные типа double и точное сравнение таких переменных простым оператором равенства вряд ли возможно. Тем более, что значение переменной ratio получено после операции деления.

Это очень странный код для приложения «Калькулятор». Поэтому прикладываю весь список предупреждений этого типа:

  • V550 An odd precise comparison. It’s probably better to use a comparison with defined precision: fabs(A — B) < Epsilon. CalcManager UnitConverter.cpp 752
  • V550 An odd precise comparison: stod(roundedString) != 0.0. It’s probably better to use a comparison with defined precision: fabs(A — B) > Epsilon. CalcManager UnitConverter.cpp 778
  • V550 An odd precise comparison. It’s probably better to use a comparison with defined precision: fabs(A — B) < Epsilon. CalcManager UnitConverter.cpp 790
  • V550 An odd precise comparison: stod(roundedString) != 0.0. It’s probably better to use a comparison with defined precision: fabs(A — B) > Epsilon. CalcManager UnitConverter.cpp 820
  • V550 An odd precise comparison: conversionTable[m_toType].ratio == 1.0. It’s probably better to use a comparison with defined precision: fabs(A — B) < Epsilon. CalcManager UnitConverter.cpp 980
  • V550 An odd precise comparison: conversionTable[m_toType].offset == 0.0. It’s probably better to use a comparison with defined precision: fabs(A — B) < Epsilon. CalcManager UnitConverter.cpp 980
  • V550 An odd precise comparison: returnValue != 0. It’s probably better to use a comparison with defined precision: fabs(A — B) > Epsilon. CalcManager UnitConverter.cpp 1000
  • V550 An odd precise comparison: sizeToUse != 0.0. It’s probably better to use a comparison with defined precision: fabs(A — B) > Epsilon. CalcViewModel LocalizationService.cpp 270
  • V550 An odd precise comparison: sizeToUse != 0.0. It’s probably better to use a comparison with defined precision: fabs(A — B) > Epsilon. CalcViewModel LocalizationService.cpp 289
  • V550 An odd precise comparison: sizeToUse != 0.0. It’s probably better to use a comparison with defined precision: fabs(A — B) > Epsilon. CalcViewModel LocalizationService.cpp 308
  • V550 An odd precise comparison: sizeToUse != 0.0. It’s probably better to use a comparison with defined precision: fabs(A — B) > Epsilon. CalcViewModel LocalizationService.cpp 327
  • V550 An odd precise comparison: stod(stringToLocalize) == 0. It’s probably better to use a comparison with defined precision: fabs(A — B) < Epsilon. CalcViewModel UnitConverterViewModel.cpp 388

Подозрительная последовательность функций

V1020 The function exited without calling the ‘TraceLogger::GetInstance().LogNewWindowCreationEnd’ function. Check lines: 396, 375. Calculator App.xaml.cpp 396

void App::OnAppLaunch(IActivatedEventArgs^ args, String^ argument)
{
  ....
  if (!m_preLaunched)
  {
    auto newCoreAppView = CoreApplication::CreateNewView();
    newCoreAppView->Dispatcher->RunAsync(....([....]()
    {
      TraceLogger::GetInstance().LogNewWindowCreationBegin(....); // <= Begin
      ....
      TraceLogger::GetInstance().LogNewWindowCreationEnd(....);   // <= End
    }));
  }
  else
  {
    TraceLogger::GetInstance().LogNewWindowCreationBegin(....);   // <= Begin

    ActivationViewSwitcher^ activationViewSwitcher;
    auto activateEventArgs = dynamic_cast<IViewSwitcherProvider^>(args);
    if (activateEventArgs != nullptr)
    {
      activationViewSwitcher = activateEventArgs->ViewSwitcher;
    }

    if (activationViewSwitcher != nullptr)
    {
      activationViewSwitcher->ShowAsStandaloneAsync(....);
      TraceLogger::GetInstance().LogNewWindowCreationEnd(....);   // <= End
      TraceLogger::GetInstance().LogPrelaunchedAppActivatedByUser();
    }
    else
    {
      TraceLogger::GetInstance().LogError(L"Null_ActivationViewSwitcher");
    }
  }
  m_preLaunched = false;
  ....
}

Диагностика V1020 анализирует блоки кода и эвристически пытается найти ветви, в которых забыт вызов функции.

В приведённом выше фрагменте кода анализатор нашёл блок с вызовом функций LogNewWindowCreationBegin и LogNewWindowCreationEnd. Ниже он нашёл похожий блок кода, в котором функция LogNewWindowCreationEnd вызывается только при определённых условиях, что подозрительно.

Ненадёжные тесты

V621 Consider inspecting the ‘for’ operator. It’s possible that the loop will be executed incorrectly or won’t be executed at all. CalculatorUnitTests UnitConverterViewModelUnitTests.cpp 500

public enum class NumbersAndOperatorsEnum
{
  ....
  Add = (int) CM::Command::CommandADD,   // 93
  ....
  None = (int) CM::Command::CommandNULL, // 0
  ....
};

TEST_METHOD(TestButtonCommandFiresModelCommands)
{
  ....
  for (NumbersAndOperatorsEnum button = NumbersAndOperatorsEnum::Add;
       button <= NumbersAndOperatorsEnum::None; button++)
  {
    if (button == NumbersAndOperatorsEnum::Decimal ||
        button == NumbersAndOperatorsEnum::Negate ||
        button == NumbersAndOperatorsEnum::Backspace)
    {
      continue;
    }
    vm.ButtonPressed->Execute(button);
    VERIFY_ARE_EQUAL(++callCount, mock->m_sendCommandCallCount);
    VERIFY_IS_TRUE(UCM::Command::None == mock->m_lastCommand);
  }
  ....
}

Анализатор обнаружил цикл for, в котором не выполняется ни одна итерация, а, следовательно, не выполняются и тесты. Начальное значение счётчика цикла button (93) сразу превышает конечное (0).

V760 Two identical blocks of text were found. The second block begins from line 688. CalculatorUnitTests UnitConverterViewModelUnitTests.cpp 683

TEST_METHOD(TestSwitchAndReselectCurrentlyActiveValueDoesNothing)
{
  shared_ptr<UnitConverterMock> mock = make_shared<UnitConverterMock>();
  VM::UnitConverterViewModel vm(mock);
  const WCHAR * vFrom = L"1", *vTo = L"234";
  vm.UpdateDisplay(vFrom, vTo);
  vm.Value2Active = true;
  // Establish base condition
  VERIFY_ARE_EQUAL((UINT)1, mock->m_switchActiveCallCount);
  VERIFY_ARE_EQUAL((UINT)1, mock->m_sendCommandCallCount);
  VERIFY_ARE_EQUAL((UINT)1, mock->m_setCurUnitTypesCallCount);
  vm.Value2Active = true;
  VERIFY_ARE_EQUAL((UINT)1, mock->m_switchActiveCallCount);
  VERIFY_ARE_EQUAL((UINT)1, mock->m_sendCommandCallCount);
  VERIFY_ARE_EQUAL((UINT)1, mock->m_setCurUnitTypesCallCount);
}

Ещё один тест с подозрительным кодом. Анализатор обнаружил идентичные фрагменты кода, выполняющиеся друг за другом. Возможно, код писался копированием этих фрагментов, но программист забыл изменить часть кода.

V601 The ‘false’ value is implicitly cast to the integer type. Inspect the second argument. CalculatorUnitTests CalcInputTest.cpp 352

Rational CalcInput::ToRational(uint32_t radix, int32_t precision) { .... }

TEST_METHOD(ToRational)
{
  ....
  auto rat = m_calcInput.ToRational(10, false);
  ....
}

В функцию ToRational передают булевское значение false, хотя параметр имеет тип int32_t и называется precision.

Я решил отследить используемое значение в коде. Далее оно передаётся в функцию StringToRat:

PRAT StringToRat(...., int32_t precision) { .... }

а затем в StringToNumber:

PNUMBER StringToNumber(...., int32_t precision)
{
  ....
  stripzeroesnum(pnumret, precision);
  ....
}

И вот тело нужной функции:

bool stripzeroesnum(_Inout_ PNUMBER pnum, long starting)
{
  MANTTYPE *pmant;
  long cdigits;
  bool fstrip = false;

  pmant=pnum->mant;
  cdigits=pnum->cdigit;
  
  if ( cdigits > starting ) // <=
  {
    pmant += cdigits - starting;
    cdigits = starting;
  }
  ....
}

Тут мы видим, что переменная precision стала называться starting и участвует в выражении cdigits > starting, что очень странно, ведь туда изначально передали значение false.

Избыточность

V560 A part of conditional expression is always true: NumbersAndOperatorsEnum::None != op. CalcViewModel UnitConverterViewModel.cpp 991

void UnitConverterViewModel::OnPaste(String^ stringToPaste, ViewMode mode)
{
  ....
  NumbersAndOperatorsEnum op = MapCharacterToButtonId(*it, canSendNegate);

  if (NumbersAndOperatorsEnum::None != op)      // <=
  {
    ....
    if (NumbersAndOperatorsEnum::None != op &&  // <=
        NumbersAndOperatorsEnum::Negate != op)
    {
      ....
    }
    ....
  }
  ....
}

Переменная op уже сравнивалась со значением NumbersAndOperatorsEnum::None и дублирующую проверку можно удалить.

V728 An excessive check can be simplified. The ‘(A && B) || (!A && !B)’ expression is equivalent to the ‘bool(A) == bool(B)’ expression. Calculator Calculator.xaml.cpp 239

void Calculator::AnimateCalculator(bool resultAnimate)
{
  if (App::IsAnimationEnabled())
  {
    m_doAnimate = true;
    m_resultAnimate = resultAnimate;
    if (((m_isLastAnimatedInScientific && IsScientific) ||
        (!m_isLastAnimatedInScientific && !IsScientific)) &&
        ((m_isLastAnimatedInProgrammer && IsProgrammer) ||
        (!m_isLastAnimatedInProgrammer && !IsProgrammer)))
    {
      this->OnStoryboardCompleted(nullptr, nullptr);
    }
  }
}

Это гигантское условное выражение изначально имело ширину 218 символов, но я разбил его на несколько строк для демонстрации предупреждения. А переписать код можно до такого короткого и, главное, читабельного варианта:

if (   m_isLastAnimatedInScientific == IsScientific
    && m_isLastAnimatedInProgrammer == IsProgrammer)
{
  this->OnStoryboardCompleted(nullptr, nullptr);
}

V524 It is odd that the body of ‘ConvertBack’ function is fully equivalent to the body of ‘Convert’ function. Calculator BooleanNegationConverter.cpp 24

Object^ BooleanNegationConverter::Convert(....)
{
    (void) targetType;    // Unused parameter
    (void) parameter;    // Unused parameter
    (void) language;    // Unused parameter

    auto boxedBool = dynamic_cast<Box<bool>^>(value);
    auto boolValue = (boxedBool != nullptr && boxedBool->Value);
    return !boolValue;
}

Object^ BooleanNegationConverter::ConvertBack(....)
{
    (void) targetType;    // Unused parameter
    (void) parameter;    // Unused parameter
    (void) language;    // Unused parameter

    auto boxedBool = dynamic_cast<Box<bool>^>(value);
    auto boolValue = (boxedBool != nullptr && boxedBool->Value);
    return !boolValue;
}

Анализатор обнаружил две функции, которые реализованы одинаково. По названиям функций Convert и ConvertBack можно предположить, что они должны выполнять разные действия, но разработчикам виднее.

Заключение

Наверное, каждый открытый проект от Microsoft давал нам возможность показать важность применения методологии статического анализа. Даже на таких маленьких проектах, как калькулятор. В таких крупных компаниях, как Microsoft, Google, Amazon и других, работает много талантливых программистов, но они такие же люди, которые делают ошибки в коде. Применение инструментов статического анализа кода — один из хороших способов повысить качество программ в любых командах разработчиков.

Проверь свой «Калькулятор», скачав PVS-Studio и попробовав на своём проекте. :-)

Если хотите поделиться этой статьей с англоязычной аудиторией, то прошу использовать ссылку на перевод: Svyatoslav Razmyslov. Counting Bugs in Windows Calculator

Get your calculator working properly again with our quick guide

by Ivan Jenic

Passionate about all elements related to Windows and combined with his innate curiosity, Ivan has delved deep into understanding this operating system, with a specialization in drivers and… read more


Updated on

Reviewed by
Vlad Turiceanu

Vlad Turiceanu

Passionate about technology, Windows, and everything that has a power button, he spent most of his time developing new skills and learning more about the tech world. Coming… read more

  • The Calculator is the default calculator app on Windows operating system.
  • To fix the problems with Calculator, you just need to reinstall it or update Windows to the latest version.
  • Errors can be caused by a calculator that is out of date, missing or error-ridden Registry and System files, or a User Account conflict.
  • If your calculator isn’t working properly, isn’t opening, is frozen, we’re here to assist you in resolving the issues.

Calculator X8 windows 10

Just like the previous versions of Windows, Windows 10 comes with some of the default apps such as a text editor, calendar, and Calculator. Speaking of which, some users are having certain issues and report that Windows 10 Calculator won’t work.

We have all used Windows Calculator, it’s a simple application that allows us to perform a quick calculations, so it’s unusual to see that the Calculator application isn’t working for some users.

If you’re having problems with Calculator on Windows 10 here are a few solutions that might help you.

Why does my Calculator not work on Windows 10?

There are many problems with Calculator that can occur on Windows 10, and in this article, we’ll show you how to fix the following issues:

  • Windows 10 Calculator doesn’t run, start, launch
    • Many users reported that the Calculator app won’t start at all on their Windows 10 PC.
    • According to them, the application is completely unresponsive.
  • The calculator won’t open on Windows 10
    • This is another variation of this problem, and many users reported that their Calculator app is unable to open.
    • This can be an annoying problem, but you should be able to fix it with one of our solutions.
  • Windows 10 Calculator opens then closes
    • Few users reported that Calculator on their PC opens and then instantly closes.
    • This is a standard problem, and you might be able to solve it by fixing corrupted files.
  • Windows 10 Calculator not working administrator
    • In some cases, the Calculator app might not work even if you’re using an administrator account.
    • To fix this problem, you need to reinstall the application.
  • Windows 10 Calculator crash, closes
    • Many users reported that their calculator frequently crashes or closes.
    • This can be an annoying problem, but you can fix it by using one of our solutions.

How can I fix the calculator not working in Windows 10?

In this article

  • Why does my Calculator not work on Windows 10?
  • How can I fix the calculator not working in Windows 10?
  • 1. Re-register Windows 10 apps using PowerShell
  • 2. Create a new user account
  • 3. Perform an SFC scan
  • 4. Install the missing updates
  • 5. Reinstall the Calculator app
  • 6. Uninstall the Calculator app
  • 7. Download the Windows app troubleshooter
  • 8. Turn off your firewall
  • 9. Enable User Account Control
  • 10. Reset the Calculator app
  • 11. End RuntimeBroker.exe process

1. Re-register Windows 10 apps using PowerShell

  1. In the Search Bar type PowerShell and right-click PowerShell app from the list of results.
  2. From the menu choose Run as administrator.
    run as administrator powershell calculator doesn't work
  3. When the PowerShell starts, paste the following line and press Enter to run it:
    • Get-AppXPackage -AllUsers | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)AppXManifest.xml"} powershell Calculator won't open in Windows 10
  4. This will re-register all Windows 10 apps on your computer. Wait for the process to finish and then try running Calculator again.

2. Create a new user account

  1. In the Search bar type add user and choose Add, edit, or remove other users from the list of results. You could also do that by going to the Settings > Accounts >Family & other users.
    add user calculator doesn't work windows 10
  2. In the Family & other users section click the Add someone else to this PC.
    add someone else to this pc Windows 10 Calculator not working administrator
  3. Click on I don’t have this person’s sign-in information.
    I don't have this person's sign-in information Windows 10 Calculator crash
  4. Now click on Add a user without a Microsoft account.
    add a user without a Microsoft account Windows 10 Calculator doesn't start
  5. Now you need to enter username and password for local account.
    user information calculator doesn't work
  6. After you’ve created a new account switch to it.

If everything works, you can delete your old account, but remember to copy your personal files and documents to your new account. This might be a bit drastic solution, but it should help you if the Calculator doesn’t work on Windows 10.

3. Perform an SFC scan

  1. Press Windows Key + X to open Win + X menu. Now choose Command Prompt (Admin) from the list of results. If Command Prompt isn’t available, you can use PowerShell (Admin) instead.
    command prompt calculator app doesn't work
  2. When Command Prompt opens, enter sfc /scannow and press Enter.
  3. SFC scan will now start. The scanning process can take up to 15 minutes, so don’t interrupt it.

Once the scan is completed, check if the issue is resolved. If SFC can’t fix the problem or if you’re unable to run SFC scan, you need to use DISM instead.

  1. To do that, start Command Prompt as administrator.
  2. Now paste DISM /Online /Cleanup-Image /RestoreHealth command and run it.
  3. Wait while Windows performs the DISM scan.

The scan process can take up to 10-20 minutes, so don’t interrupt it.

Once the DISM scan is finished, the issue should be resolved. If you were unable to run an SFC scan before, run it after running a DISM scan and check if that solves your problem.

4. Install the missing updates

  1. Press Windows Key + I to open the Settings app.
  2. When the Settings app opens, navigate to the Update & security section.
    update and security Windows 10 Calculator not working administrator
  3. Click on the Check for updates button. Windows will now check for available updates. If updates are available, they will be downloaded automatically in the background.
    check for updates Windows 10 Calculator closes

Installing the latest updates can fix bugs and glitches that can cause the Calculator to stop working.

5. Reinstall the Calculator app

Open the Microsoft Store from the Start menu and reinstall the Calculator app. If you need more guidance, be sure to check our article on how to reinstall Windows Store apps.

6. Uninstall the Calculator app

If establishing a new user account in Windows Calculator does not resolve the issue, you can uninstall it.

Because you can’t do it the ordinary way, you’ll need to use an advanced method to reinstall Windows Calculator using an excellent uninstaller application like IObit Uninstaller.

IObit Uninstaller is a helpful uninstallation tool for PCs that runs great on Microsoft Windows apps. It removes any unwanted programs with all associated files for better PC performance. 

Simply launch IObit Uninstaller after downloading it and choose All programs from the left panel. You’ll notice a list of all your applications there, where you’ll easily select the Calculator app, and click the trash icon to completely remove it from the Windows operating system.

 Get IObit Uninstaller

7. Download the Windows app troubleshooter

  1.  Download Windows apps troubleshooter.
  2. After downloading the tool, run it and let it scan your PC.
  3. If the troubleshooter finds any issues with your apps, it will automatically fix them.

If Calculator doesn’t work in Windows 10, using the Windows app troubleshooter is one of the simplest and fastest ways to fix it.

8. Turn off your firewall

  1. Press Windows Key + S and enter firewall. Select Windows Firewall from the list of results.
    windows defender firewall windows calculator doesn't work
  2. Click on Turn Windows Firewall on or off in the menu on the left.
    turn off windows firewall Calculator won't open in Windows 10
  3. Now select Turn off Windows Firewall (not recommended) for both Private and Public network settings. Click on OK to save changes.
    Turn off windows firewall calculator doesn't work Windows 10

After disabling your firewall, check if the issue still appears. If not, you might want to enable your firewall and create a security exception for the Calculator app and check if that solves the problem. In case you use a third-party firewall, as a part of antivirus software, try disabling it instead.

9. Enable User Account Control

  1. Press Windows Key + S and enter user account control. Select Change User Account Control settings.
    change User account control settings Windows 10 calculator doesn't work
  2. Move the slider to the default position and click on OK to save changes.
    user account control slider calculator doesn't work windows 10

Few users reported that Calculator doesn’t work if User Account Control is disabled, so by enabling it you should be able to fix the problem.

10. Reset the Calculator app

1. Open the Settings app. You can do this by inputting settings in the Windows Search box and pressing Enter.

2. Go to the Apps section. A list of all applications will now appear.

go to apps

3. Select Calculator and click on Advanced options.

go to calculator

4. Now click on the Reset button.

reset calculator button

5. Select Reset again in the confirmation window. After doing that, the problem should be resolved and you’ll be able to use Calculator without any issues.

When your Windows 10 calculator is not working properly, another quick fix is simply resetting the Calculator app.

This can be done via Settings in just a few clicks and should solve any problems related to the app.

11. End RuntimeBroker.exe process

Sometimes background processes can cause issues with the Calculator app. If Calculator doesn’t work on your Windows 10 PC, the cause might be the RuntimeBroker.exe process.

To fix the issue, you need to end this process by doing the following:

  1. Press Ctrl + Shift + Esc to open Task Manager.
  2. When Task Manager starts, locate Runtime Broker, right-click it, and choose End task from the menu.
    end task runtime broker Windows 10 Calculator not working administrator

After ending the Runtime Broker process, check if the issue is resolved. Keep in mind that this is just a workaround, so you might have to repeat this solution if the issue reappears.

Tip icon
Tip

We covered Calculator updates and issues in the past, so if you’re having any other problems with it, be sure to check our Calculator hub for more information. If you’re having additional Windows 10 issues, we advise that you check out our Windows 10 errors hub for more helpful articles.

That would be all, I hope this article helped you with calculator problems in Windows 10. If you have any comments or questions, just reach out to the comment section below

newsletter icon

Операционная система Windows 10 включает в себя встроенное приложение калькулятор. Новое приложение калькулятор заменило программу классического калькулятора, но возможность запустить классический калькулятор в Windows 10 осталась.

Калькулятор не работает или не открывается в Windows 10?

Как и другие встроенные приложения, приложение калькулятор иногда может не запускаться или сразу закрывается после запуска. Если у вас возникли проблемы с приложением Калькулятор, следующие шаги могут помочь вам исправить универсальное приложение калькулятор в Windows 10.


 

 Способ 1. 

Сбросить параметры приложения Калькулятор.

В Параметрах Windows 10 существует возможность для сброса настроек приложений. Если приложение Калькулятор работает не правильно, сбросьте его настройки.

Шаг 1: Откройте «Параметры» Windows, нажав сочетание клавиш Win + I, 

Перейдите — «Параметры»  →  «Приложения» →  «Приложения и возможности».

Шаг 2: Найдите запись приложения Калькулятор. Выберите приложение Калькулятор, нажав на него. Теперь вы должны увидеть ссылку «Дополнительные параметры». Нажмите ссылку, открыв страницу сброса приложения.

Шаг 3: Здесь, нажмите кнопку «Сбросить». Откроется окно подтверждения, нажмите кнопку Сбросить еще раз, чтобы полностью сбросить настройки приложения Калькулятор.

Способ 2.

Переустановите приложение калькулятор в Windows 10

Если проблема с запуском приложения сохраняется, даже после сброса настроек приложения, вы можете рассмотреть возможность переустановки калькулятора. Поскольку Windows 10 не предлагает простой способ для удаления калькулятора, вам необходимо использовать PowerShell чтобы удалить приложение перед повторной установкой его же из магазина Windows. См.

Эту статью: Как удалить универсальные приложения в Windows 10.

Чтобы переустановить приложение «Калькулятор», вы должны указать специальную команду PowerShell, как описано ниже.

  1. Откройте PowerShell в качестве администратора.
  2. Скопируйте и вставьте следующую команду:  
 Get-AppxPackage *WindowsCalculator* | Remove-AppxPackage

Эта команда удалит современное приложение Калькулятор.

  1. Теперь откройте Магазин Microsoft и установите калькулятор. Введите «Калькулятор» в поле поиска, чтобы установить официальное приложение.

Совет. Вот прямая ссылка на официальное приложение Калькулятор.

Калькулятор Windows в Microsoft Store

Вот и все, надеюсь, теперь приложение будет работать как надо.

Способ 3.

Запустите восстановление системы Windows 10.

Если ни один из вышеперечисленных способов не исправил проблему калькулятора, можно востановить Windows 10, для решения данной проблемы. Тем не менее, помните, что при восстановлении Windows 10 удалятся все установленные сторонние программы и приложения. См, Как переустановить Windows 10 без потери данных.

Способ 4.

Установите программу Калькулятор стороннего разработчика 

Если встроенный калькулятор не работает даже после всех способов упомянутых выше, вы можете установить — Calculator Plus одно  из многих приложений из магазина Windows 10. 

Калькулятор — одно из самых популярных приложений в компьютерной программе Windows Home. Он предоставляет пользователю возможность выполнения различных математических операций, как простых, так и сложных. Несмотря на то, что калькулятор считается довольно стабильным приложением, есть несколько известных ошибок (багов), которые пользователи могут встретить при его использовании.

1. Проблема с округлением

Один из наиболее распространенных багов калькулятора в Windows Home связан с округлением. Во многих случаях калькулятор округляет результаты математических операций до определенного числа знаков после запятой, что может привести к неточным результатам. Например, при вычислении выражения «0.1 + 0.2» калькулятор может показать результат «0.30000000000000004» вместо ожидаемого «0.3».

2. Проблемы со скобками

Еще одной распространенной ошибкой калькулятора в Windows Home является некорректная обработка скобок.

Иногда при использовании скобок в выражениях, калькулятор может выдавать неправильный результат, даже если выражение вводится корректно. Это может создать проблемы при выполнении сложных математических операций, особенно если они требуют использования скобок для задания порядка операций.

3. Ошибки с делением на ноль

Одной из наиболее серьезных ошибок калькулятора в Windows Home является возможность деления на ноль без предупреждения или соответствующих сообщений об ошибке. При попытке выполнить операцию деления на ноль, калькулятор может просто показать некорректный результат или даже зависнуть, не реагируя на дальнейшие действия пользователя.

4. Проблема с памятью и историей

Еще одной проблемой калькулятора в Windows Home является ограниченная емкость памяти или недостаточная история для отслеживания предыдущих операций. Если пользователь выполняет большое количество операций или пытается просмотреть историю предыдущих вычислений, он может обнаружить, что калькулятор перестает сохранять все операции или не позволяет выполнить новые вычисления из-за ограничений памяти.

5. Ошибки с клавишами и интерфейсом

Калькулятор в Windows Home также может столкнуться с ошибками, связанными с клавишами и интерфейсом. К примеру, возможно нажатие клавиш не приведет к выполнению соответствующих математических операций, или наоборот — выполнится непреднамеренная операция из-за ошибочного нажатия.

Заключение

Несмотря на некоторые ошибки и баги, обычный стандартный калькулятор в Windows Home по-прежнему является удобным и полезным инструментом для большинства пользователей. Однако, при выполнении сложных или критически важных математических операций, рекомендуется использовать более надежное и точное программное обеспечение.

  • Подскажите, пожалуйста, ошибки (баги) обычного стандартного калькулятора в Windows Home?
  • Да чем вообще азиатки могут возбуждать? Вы че?
  • Со мной по соседству живёт джин: настоящий с хохлом
  • Может ли девушка закрутить роман в отпуске на море, даже если у нее есть парень?
  • Вопрос по игре Ведьмак 2: убийцы королей
  • Народ, неужели тяжело пройти по ссылке!!!
  • Помогите написать регулярное выражение…
  • Кому водки налить, а то все гости разбрелись

Windows 11 calculator is creating many problems such as the app surprisingly crashes, opens then immediately closes, or not performs as expected. Some people complain that the built-in Microsoft Store application does not work after they have received an update. Don’t worry, this post covers the methods for how to fix all calculator issues in windows 11 Laptop/PC.

Commonly, Calculator not working in Windows 11 occurs because of a buggy update your system might have installed recently. Furthermore, corrupted system files, incorrect registry entry, user account, Windows Firewall may also be reasons for the problem. Sometimes, a simple trick works like a wonder to fix the calculator app; we will also put this forward in the following part.

Here is how to fix Calculator not working in Windows 11 –

Way-1: Update Calculator

Windows calculator is a simple app yet pretty much useful in Standard, Scientific, Graphing, or programmer mode. The program often receives updates being a Store app. Calculator not working in Windows 11 may occur if you don’t update the app. In order to fix this issue, try to update calculator app from Microsoft Store. Follow the below guidelines –

  1. Click the Start icon in the Taskbar.
  2. When the Start menu opens, click Microsoft Store icon.

how to fix Calculator not working in Windows 11

  1. Once on the Store app, click the lined Library on the left pane.
  2. Click – Get updates.

update calculator app

  1. In a while, downloading and installing the update for the Calculator app will be completed.
  2. Now open Windows Calculator from the list in the Store library. You can also open from Start.
  3. Check if it is running normally now.

Way-2: Remove problematic Windows Update

Many times, you may notice Windows 11 calculator not working after update issue. This problem occurs mostly because of bugs. The Tech giant delivers updates for the operating system quite regularly with modifications, security improvements, and built-in tools. Some of these updates might not support a few programs including Windows calculator.

Windows 11 has an easier method to uninstall a troublesome patch without making even the slightest change to the machine. Therefore, in order to fix calculator not working in Windows 11 issue follow the steps –

  1. Press – Windows+R.
  2. Type appwiz.cpl in the Run dialog box.

Remove problematic Windows Update

  1. Press Enter key to open up Program and Features window.
  2. From the left side pane, click View installed updates link.
  3. Look for the last installed patch and right-click on it.
  4. Select “Uninstall”.

 fix Calculator not working in Windows 11

  1. Click Yes from the pop-up again.

Way-3: Run Store app troubleshooter

Calculator is a default Store app in Windows 11 and it comes pre-installed in the system. For such programs, running Store troubleshooter will be the easiest solution to fix this glitch.

Windows 11 has a bunch of necessary tools and troubleshooters to fix an issue using built-in resources. However, we will now run the Microsoft Store app troubleshooter to fix the calculator issue. Follow the below steps to accomplish this task –

  1. Press Windows key and I at once.
  2. From the Settings app, select System located on the left.
  3. On the right, click – Troubleshoot.

troubleshoot calculator

  1. Upon opening the additional settings page, click – Other troubleshooters.

Other troubleshooters

  1. Go down to Others section on the following page and find Windows Store Apps.
  2. Click on Run.

store app troubleshooter

  1. The troubleshooter will start detecting trouble and will fix it automatically.
  2. Check if the Calculator issue doesn’t persist.

Way-4: End the RuntimeBroker.exe Process to fix Windows 11 Calculator problem

Oftentimes, a few applications don’t run in Windows because some of the background processes don’t allow them to start. RuntimeBroker.exe is one such process that may prevent Calculator app from opening and you get the not working issue in the end.

In order to fix this trouble, you have to end this process immediately after coming across.

  1. Press Ctrl + Shift + Esc.
  2. When the Task Manager opens, find the – Runtime Broker.
  3. Right click on the process and select End task.

Calculator not working

  1. After the process is ended, try reopening the Calculator app and check if it behaves in good way.

Way-5: Reset Calculator app

Windows 11 has a specialized feature to reset an app and this is advantageous when it is causing trouble in opening or operation. If you are having issues with the calculator app, try resetting it.

Windows 11 calculator settings will back to the original state after you reset it. To perform this task, follow the below instructions –

  1. Click the – Start.
  2. On the Start menu and click Gear icon which indicates Settings.
  3. When the Settings app opens, click Apps from left side pane.
  4. Click Apps & features from the right.

Reset Calculator app

  1. In the Search bar under App list, type calculator.
  2. Click on three-dotted menu when the app appears.
  3. Choose Advanced options from the context.

Advanced options

  1. After being guided to the next page, move down to the “Reset” area.
  2. Click Reset.
  3. Again select the ‘Reset’ when asked in the popup.

Calculator not working in Windows 11

  1. Restart the Window 11.
  2. Check if the calculator is working without a problem now.

Way-6: Reinstall Calculator app

Reinstalling the application is yet another great idea to fix calculator not working in Windows 11 issue. In the above workaround, you have performed resetting the Windows app which actually deletes all the user data and makes it like it was never been used. In case that resolution fails to fix the malfunction of the program, you can always uninstall it. Later on, install the same from Microsoft Store to start it afresh in the system.

To re-install an application in Windows 11, here are the guidelines –

  1. Open Settings.
  2. Click – Apps.
  3. From the right pane, click – Apps & features.
  4. When on the next page find – Calculator.
  5. Click on the 3-dots menu.
  6. Select – Uninstall.
  7. Confirm the selection by clicking “Uninstall” on popup.

uninstall calculator

  1. Once the process ends, Restart Windows 11.
  2. Calculator Windows 11 download and install from Microsoft Store.

Furthermore, you can see How to Get Offline Installer for Store App in Windows 10 to download Windows calculator manually and install it.

Way-7: Windows 11 calculator registry fix

If you are having calculator not working in Windows 11 issue, try deleting certain keys in Windows Registry. For that, follow the below guidelines –

  1. Press – Windows.
  2. Type – regedit.
  3. Hit – Enter.
  4. Navigate to the below path –
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModel\StateChange\PackageList
  1. Expand the PackageList path and delete all the keys under it.

solve Calculator not working in Windows 11

  1. Restart your computer calculator issue will no longer occur.

Way-8: Create a local account

Sometimes, calculator not working in Windows 11 when logging in with administrator account. If the issue occurs just after starting a new computer, it might be a problem related to User Account. In order to fix this trouble, you to add a local account and log into it.

  1. Press Window + X.
  2. Choose Settings.
  3. Select Accounts from the left column.
  4. Move to the right-hand side and click Family & other users.
  5. Click Add account present for Add other user.
  6. In the next prompt, select – I don’t have this person’s sign-in information.
  7. On the next pop up, click on – Add a user without a Microsoft account.
  8. Follow further on-screen instructions to complete the process.
  9. Once done, reboot Windows 11.
  10. When the system powers up, login with the new user account.

Way-9: Enable User Account Control

User Account Control aka UAC in Windows 11 is a basic component in order to control overall security in the machine. Commonly, the functionality is enabled by default in Windows. Before making any changes to the computer, a popup arises asking permission from the admin to proceed. This is annoying often especially when you are in a hurry to complete a task on Windows. Therefore, some users disable the security feature for the time being and forgot to turn back On.

However, Calculator issue in Windows 11 can also happen in your system if the UAC is not enabled. Therefore, enable this by following below steps –

  1. Press – Windows key
  2. Type control panel.
  3. Hit – Enter.
  4. From the Control panel, click User Accounts.
  5. From the following window, click the Change User Account Control settings link.
  6. When a popup opens, move the slider to Always notify.
  7. Click Ok from below.
  8. When UAC prompts for permission, click Yes to proceed.
  9. Open the Calculator app now and check if it is working well.

Way-10: Check for Windows Update to fix Windows 11 calculator problem

Windows Update is an essential task in Operating System to keep it running smoothly and in healthy condition. On the contrary, outdated Operating System renders a lot of troubles, causes unexpected lags and malfunction in the programs. It may too happen that, Calculator not working in Windows 11 is occurring as you haven’t installed the pending updates.

Therefore, carry out a check for updates from the Settings app by following the steps –

  1. Press Windows key and I together.
  2. In the Settings app, click Windows Update from the left pane.
  3. Click – Check for updates.
  4. Windows Will carry out a scan for pending update files.
  5. Downloading followed by installing the updates will take place automatically.
  6. Click Restart now once you are asked.

Way-11: Run SFC Scan

System components are very much sensitive and prone to get corrupted by malware infection. Some other reasons like sudden power surge, power outage, Windows updating error make them damaged too. System files may also go missing along with .dll files quite often. In many cases, Windows 11 calculator opens then immediately closes. This crashing might occur because of corruption in system files.

This way you can say that corrupted and missing system files are responsible for calculator problem Windows 11 issue. Running SFC scan will detect the broken components and recover the missing ones. You have to run command line tool in Elevated Command Prompt for performing this scan. Here are the steps –

  1. Press – Windows key.
  2. Type – cmd.
  3. When Command Prompt appears in the result, right-click on it.
  4. Select – Run as Administrator.
  5. Click – Yes after the UAC pops out for permission.
  6. On the Elevated Command Prompt, type – Sfc /scannow.
  7. Press – Enter.
  8. Windows will run the System File Checker. At the end of the process, all the missing files will be recovered and fixed.
  9. Restart Windows 11 once the process ends.

Way-12: Fix Calculator not working in Windows 11 using PowerShell

Reinstalling the Calculator app is one of the most useful fixes we have found out to fix the not working issue. Dissimilar to Way-6, we can also re-install the program using PowerShell commands.

  1. Right-click on Start.
  2. Select – Windows Terminal (Admin).
  3. Click Yes when UAC prompts up for permission.
  4. When the PowerShell window rolls out, copy-paste the below command –

get-appxpackage *Microsoft.WindowsCalculator* | remove-appxpackage

  1. Press Enter key and the system will uninstall Windows Calculator app.
  2. Once the removal ends, Restart Windows.
  3. Install Calculator app and check if it is working fine.

Way-13: Run DISM scan

We have got to know that missing system components and corrupted Windows files can also cause calculator not working in Windows 11 issue. However, Windows image files are named behind the problem too once these components are found in corrupted condition.

DISM scan stands for Deployment Image Servicing and Management is an administrative tool intended to rectify corrupted Windows image files. We will now try running this tool in order to fix the calculator app error. For that, you have to manage to enter the Elevated Command Prompt first.

  1. Open Command Prompt as administrator.
  2. Type in the below command –

DISM /Online /Cleanup-Image /RestoreHealth

  1. Press – Enter key.
  2. When the scanning ends, the utility will rectify corrupted Windows image files if detected automatically.
  3. Restarting the machine and see the condition of the Calculator app.

Way-14: Disable Windows Firewall temporarily

Windows Firewall is a feature built to decontaminate the incoming data to your system from internet. The functionality will block potentially harmful programs and websites if found suspicious. The application has a tendency to preclude most of the apps coming across it unless allowed by the user in a list.

However, Windows Firewall may also block the calculator app suspecting it as harmful. In the end, you will get a calculator not working in Windows 11 issue. Though it is not always recommended to disable Windows Firewall for security reasons, we urge you to do it temporally.

  1. Press Windows key and R together.
  2. In the Run dialog box, type control panel.
  3. Click on the OK.
  4. Next, click – Windows Defender Firewall.
  5. When the following page opens up, select – Turn Windows Defender Firewall on or off from the left pane.
  6. From the next window, click the radio button set for Turn off Windows Defender Firewall (not recommended).
  7. Click OK to save the changes.

How to Fix Calculator not working in Windows 11

Methods list:
Way-1: Update Calculator
Way-2: Remove problematic Windows Update
Way-3: Run Store app troubleshooter
Way-4: End the RuntimeBroker.exe Process
Way-5: Reset Calculator app
Way-6: Reinstall Calculator app
Way-7: Tweak Windows Registry and delete certain keys
Way-8: Create a new user account and log in
Way-9: Enable User Account Control
Way-10: Check for Windows Update
Way-11: Run SFC Scan
Way-12: Re-install Calculator app using PowerShell
Way-13: Run DISM scan
Way-14: Disable Windows Firewall temporarily

That’s all!!

Repair any Windows problems such as Blue/Black Screen, DLL, Exe, application, Regisrty error and quickly recover system from issues using Reimage.

Понравилась статья? Поделить с друзьями:
  • Ошибки и осложнения при проведении реанимационных мероприятий
  • Ошибки и осложнения при применении штифтовых конструкций
  • Ошибки и осложнения при применении съемных пластиночных протезов
  • Ошибки и осложнения при применении пластмассовых коронок
  • Ошибки и осложнения при применении вкладок