2017-01-21 21 views
-1

Мне нужно рассчитать налогооблагаемый доход и по какой-то причине, когда я ввожу доход как 5000 и подавая m для вступления в брак, он дает мне немного неправильный номер. Вот мой код:Неверный номер, выводимый из циклов if

#include "stdafx.h" 
#include <iostream> 
#include <iomanip> 
#include <cmath> 

using namespace std; 

int main() 
{ 
    double calcTax = 0; 
    double income = 0; 
    char choice; 
    do { 
     //Prompt user for income 

     cout << "Please enter in your taxable income.\nThis must be a positve number:" << endl; 
     cin >> income; 
     while (income < 0) 
     { 
      cout << "Please enter a positive value" << endl; 
      cin >> income; 
     } 

     //Ask if user is filing as single or married. Continue until correct input is received 
     char status; 
     cout << "Please enter an 'm' if married and filing jointly or an 's' if single and filing alone:" << endl; 
     cin >> status; 
     while ((status != 'm') && (status != 's')) 
     { 
      cout << "You have pressed an incorrect key. Please enter an 'm' if married and filing jointly or an 's' if single and fiing alone:" << endl; 
      cin >> status; 
     } 
     double sBase1 = 863, 
      sBase2 = 2588, 
      sBase3 = 4313, 
      mBase1 = 1726, 
      mBase2 = 5176, 
      mBase3 = 8626; 

     double sAdd2 = 25, 
      sAdd3 = 85, 
      sAdd4 = 181, 
      mAdd2 = 40, 
      mAdd3 = 175, 
      mAdd4 = 390; 

     double taxRate1 = 0.023, 
      taxRate2 = 0.033, 
      taxRate3 = 0.052, 
      taxRate4 = 0.075; 



     //Calculate tax if user is single, based on income tier 
     if (status == 's') 
     { 
      if (income <= sBase1) 
      { 
       calcTax = income * taxRate1; 
      } 
      if (sBase1 < income <= sBase2) 
      { 
       calcTax = ((income - sBase1)) * taxRate2 + sAdd2; 
      } 
      if (sBase2 < income <= sBase3) 
      { 
       calcTax = ((income - sBase2) * taxRate3) + sAdd3; 
      } 
      if (sBase3 < income) 
      { 
       calcTax = ((income - sBase3) * taxRate4) + sAdd4; 
      } 
     } 

     //Calculate tax if user is married, based on income tier 
     if (status == 'm') 
     { 
      if (income <= mBase1) 
      { 
       calcTax = income * taxRate1; 
      } 
      if (mBase1 < income <= mBase2) 
      { 
       calcTax = ((income - mBase1)) * taxRate2 + mAdd2; 
      } 
      if (mBase2 < income <= mBase3) 
      { 
       calcTax = ((income - mBase2) * taxRate3) + mAdd3; 
      } 
      if (mBase3 < income) 
      { 
       calcTax = ((income - mBase3) * taxRate4) + mAdd4; 
      } 

     } 

     //Display user's tax 
     cout << "$" << fixed << setprecision(2) << calcTax << endl; 

     //Ask if user would like to calculate another tax 
     //If so, repeat until done 
     char response; 
     cout << "Would you like to perform another tax calculation (y or n)?:" << endl; 
     cin >> choice; 

     while (choice != 'n' && choice != 'y') 
     { 
      cout << "Please enter y or n" << endl; 
      cin >> choice; 
     } 


    } while (choice == 'y'); 
    return 0; 
} 

5000 и должно быть возвращено 148.04, но вместо этого я получаю 165.85. Может кто-нибудь помочь указать, что происходит не так?

+0

Я думаю, что вы бы выгоду от использования IDE с помощью отладчика , Я предлагаю загрузить Visual Studio или Eclipse. Если вы никогда не отлаживали код, найдите короткое видео на YouTube о том, как отлаживать в своей среде IDE выбор. – plukich

+0

Почему бы вам не предложить формулу, по которой вы должны рассчитать свой код? Таким образом, мы можем сравнить вашу формулу с тем, как ваша программа вычисляет налог и отслеживает ошибку. –

+0

plukich, я уже использую Visual Studio. – riahtron3000

ответ

0

Ваши причины if являются причиной такого поведения. Написание чего-то типа if (mBase1 < income <= mBase2) не имеет такого же математического значения в C++, поскольку компилятор сравнивает только два значения за раз (если я не ошибаюсь).

Так пишут:

if (mBase1 < income && income <= mBase2) вместо того, чтобы убедиться, что он должен сравнить оба заявления и убедитесь, что оба являются действительными.

Замена линии

if (mBase2 < income <= mBase3)

с if (mBase2 < income && income <= mBase3)

уже сделал трюк давая вам правильный запрос для вашего данного примера (5000 и «м). Без этого компилятор думает что-то например:

mBase2 < доход? Это неверно, но доход < = mBase3? Это верно, позволяет ввести это, если придаточного

и, таким образом переписав calcTax -value

0
You cannot compare two conditions at a time using if statement 
if(a<b<c) is similar to 
if((a<b) || (b<c) ) 
so in your program you should use && instead of comparing straight away 

пример:

#include<stdio.h> 

int main() 
{ 
    if (5 < 6) 
    { 
     printf("5 is less than 6\n"); 
    } 
    if (90 >6) 
    { 
     printf("6 is less than 90\n"); 
    } 
    if (5 < 6 <90) // here only half of the condition checking takes place ..till (5<6) and (6<90)is not verified 
    { 
     printf("5 is less than 6 and 6 is less than 90"); 
    } 

    getchar(); 
    return 0; 

} 



so change your code to---> 


#include < iostream> 

#include < iomanip> 

#include < cmath> 

using namespace std; 

int main() 
{ 

    double calcTax = 0; 

double income = 0; 

    char choice; 
    do { 
     //Prompt user for income 

     cout << "Please enter in your taxable income.\nThis must be a positve number:" << endl; 
     cin >> income; 
     while (income < 0) 
     { 
      cout << "Please enter a positive value" << endl; 
      cin >> income; 
     } 

     //Ask if user is filing as single or married. Continue until correct input is received 
     char status; 
     cout << "Please enter an 'm' if married and filing jointly or an 's' if single and filing alone:" << endl; 
     cin >> status; 
     while ((status != 'm') && (status != 's')) 
     { 
      cout << "You have pressed an incorrect key. Please enter an 'm' if married and filing jointly or an 's' if single and fiing alone:" << endl; 
      cin >> status; 
     } 
     double sBase1 = 863, 
      sBase2 = 2588, 
      sBase3 = 4313, 
      mBase1 = 1726, 
      mBase2 = 5176, 
      mBase3 = 8626; 

     double sAdd2 = 25, 
      sAdd3 = 85, 
      sAdd4 = 181, 
      mAdd2 = 40, 
      mAdd3 = 175, 
      mAdd4 = 390; 

     double taxRate1 = 0.023, 
      taxRate2 = 0.033, 
      taxRate3 = 0.052, 
      taxRate4 = 0.075; 



     //Calculate tax if user is single, based on income tier 
     if (status == 's') 
     { 
      if (income <= sBase1) 
      { 
       calcTax = income * taxRate1; 
      } 
      if (sBase1 < income <= sBase2) 
      { 
       calcTax = ((income - sBase1)) * taxRate2 + sAdd2; 
      } 
      if (sBase2 < income <= sBase3) 
      { 
       calcTax = ((income - sBase2) * taxRate3) + sAdd3; 
      } 
      if (sBase3 < income) 
      { 
       calcTax = ((income - sBase3) * taxRate4) + sAdd4; 
      } 
     } 

     //Calculate tax if user is married, based on income tier 
     if (status == 'm') 
     { 
      if (income <= mBase1) 
      { 
       calcTax = income * taxRate1; 
      } 
      if ((mBase1 < income) && (income <= mBase2)) 
      { 
       calcTax = (((income - mBase1) * taxRate2) + mAdd2); 
      } 
      if ((mBase2 < income) &&(income <= mBase3)) 
      { 
       calcTax = ((income - mBase2) * taxRate3) + mAdd3; 
      } 
      if (mBase3 < income) 
      { 
       calcTax = ((income - mBase3) * taxRate4) + mAdd4; 
      } 

     } 

     //Display user's tax 
     cout << "$" << fixed << setprecision(2) << calcTax << endl; 

     //Ask if user would like to calculate another tax 
     //If so, repeat until done 
     char response; 
     cout << "Would you like to perform another tax calculation (y or n)?:" << endl; 
     cin >> choice; 

     while (choice != 'n' && choice != 'y') 
     { 
      cout << "Please enter y or n" << endl; 
      cin >> choice; 
     } 


    } while (choice == 'y'); 
    return 0; 
} 
Смежные вопросы