Вот мой код: -
#include <iostream>
using namespace std;
int Add (int *x , int *y)
{
int a=*x;
int b=*y;
int c=a+b;
return (c);
}
int Sub (int *x , int *y)
{
int a=*x;
int b=*y;
int c=a-b;
return (c);
}
int Mul (int *x , int *y)
{
int a=*x;
int b=*y;
int c=a*b;
return (c);
}
int Div (int *x , int *y)
{
int a=*x;
int b=*y;
int c=a/b;
return (c);
}
int Mod (int *x , int *y)
{
int a=*x;
int b=*y;
int c=a%b;
return (c);
}
int InputFunction (int *a , int *b , char op)
{
int x=*a;
int y=*b;
int c=0;
cout<<"Please enter first number : ";
cin>>x;
cout<<"Please enter second number : ";
cin>>y;
cout<<endl;
cout<<"Please choose an operator to perform the operation :- "<<endl<<endl;
cout<<" \t \t \t + for addition"<<endl;
cout<<" \t \t \t - for sunbtraction"<<endl;
cout<<" \t \t \t x for mutiplication"<<endl;
cout<<" \t \t \t / for division"<<endl;
cout<<" \t \t \t % for modulus"<<endl<<endl<<endl;
cout<<" \t \t Your choice : ";
cin>>op;
switch (op)
{
case '+':
Add (&x , &y);
break;
case '-':
Sub (&x , &y);
break;
case 'x':
Mul (&x , &y);
break;
case '/':
Div (&x , &y);
break;
case '%':
Mod (&x , &y);
break;
default:
cout<<"Your symbol is not recognized!";
break;
}
int i=c;
return (i);
}
int main()
{
int a=0;
int b=0;
char op;
char ch;
int i;
do
{
InputFunction (&a , &b , op);
int m=i;
cout<<" \t \t Your answer : "<<m<<endl<<endl;
cout<<"Do you want to repeat the program ? (Y/N) ";
cin>>ch;
}while (ch == 'Y' || ch == 'y');
cout<<"Good- Bye"<<endl;
return 0;
}
Почему вычисляется какой-то странный длинный ответ? Также компилятор показывает предупреждения о том, что функции op
и i
в main()
не инициализированы (хотя они инициализированы выше). Я новичок в C++. Помощь будет оценена.
Я изменил код для вас. Фактическая проблема заключается в том, что вы не назначаете возвращаемые значения. я в вашем InpuFunction, и я в ваших основных методах отличается. Если вы не вернете значение из InputFunction (вызываемого метода) в главную функцию (метод вызывающего), ваше значение не изменится.
#include <iostream>
using namespace std;
int Add (int *x , int *y)
{
int a=*x;
int b=*y;
int c=a+b;
return (c);
}
int Sub (int *x , int *y)
{
int a=*x;
int b=*y;
int c=a-b;
return (c);
}
int Mul (int *x , int *y)
{
int a=*x;
int b=*y;
int c=a*b;
return (c);
}
int Div (int *x , int *y)
{
int a=*x;
int b=*y;
int c=a/b;
return (c);
}
int Mod (int *x , int *y)
{
int a=*x;
int b=*y;
int c=a%b;
return (c);
}
int InputFunction (char op)
{
int x;
int y;
int c=0;
cout<<"Please enter first number : ";
cin>>x;
cout<<"Please enter second number : ";
cin>>y;
cout << " x = " << x << " y = " << y << endl;
cout<<endl;
cout<<"Please choose an operator to perform the operation :- "<<endl<<endl;
cout<<" \t \t \t + for addition"<<endl;
cout<<" \t \t \t - for sunbtraction"<<endl;
cout<<" \t \t \t x for mutiplication"<<endl;
cout<<" \t \t \t / for division"<<endl;
cout<<" \t \t \t % for modulus"<<endl<<endl<<endl;
cout<<" \t \t Your choice : ";
cin>>op;
switch (op)
{
case '+':
c = Add (&x , &y);
break;
case '-':
c = Sub (&x , &y);
break;
case 'x':
c = Mul (&x , &y);
break;
case '/':
c = Div (&x , &y);
break;
case '%':
c = Mod (&x , &y);
break;
default:
cout<<"Your symbol is not recognized!";
break;
}
cout << "c is " << c << endl;
int i=c;
return (i);
}
int main()
{
char op;
char ch;
int i;
do
{
int m = InputFunction (op);
cout<<" \t \t Your answer : "<<m<<endl<<endl;
cout<<"Do you want to repeat the program ? (Y/N) ";
cin>>ch;
}while (ch == 'Y' || ch == 'y');
cout<<"Good- Bye"<<endl;
return 0;
}
int InputFunction (int *a , int *b , char op)
Вы никогда не назначаете возвращаемое значение своих функций ни на что в своем основном цикле.
то есть.,
int i = InputFuction(...);
int a = Add(1, 2);
int b = Sub(1, 2);
// etc.
У вас такая же проблема со всеми вашими функциями (Add, Sub, Mul и т.д.). Возвращаемое значение не получает никакого назначения.
Для предупреждений, когда вы объявляете локальную переменную, ее значение не задано. Это означает, что его значение неопределенно, и его использование приведет к неопределенному поведению.
Перед использованием вы должны инициализировать локальные переменные. Кстати, это может быть основной причиной вашей проблемы.
Возможно, вы захотите сделать
i = InputFunction (&a, &b, op);
Или даже лучше, вам действительно не нужна переменная i
(или op
) в main
функции, поэтому
m = InputFunction (&a, &b);
должно быть достаточно (после того, как вы измените InputFunction
чтобы не принимать аргумент op
качестве аргумента).
Что касается предупреждений компилятора, вы объявили op
и i
, но не инициализировали их значением (как и с a
& b
).
Что касается выхода, какой результат вы на самом деле получаете?
i
используется в качестве ответа операции, присвойте i
выходные данные InputFunction
, как уже отмечалось в других ответах. Для op
вы должны спросить своего пользователя, что он хочет вычислить (так же, как вы уже делаете, когда ch
означает либо «Y», либо «y»).