The following code compile without any errors, but when I try to do 2 * 1 (or any other number that isn't 1) the string "Inte ok" from the ans function isn't written on the screen the program just quits. Why is that?
//Test för att se om jag förstår funktioner
#include <iostream>
#include <string>
using namespace std;
//Deklarerar variblar som jag ska använda
int a,b,x;
string s, ab;
//Skriver ut funktionen för att multiplicera
int multi(int a, int b)
{
x = a * b;
return x;
}
string ans()
{
using std::string;
string s = "Inte ok";
ab = s;
return ab;
}
//Samlar in värde från användaren, skickar den till funtktionen "multi" som multiplicerar den, sedan skickar den tillbaks den till main via return. Main visar sedan
//resultatet för användaren
int main( void )
{
using std::cout;
using std::cin;
using std::string;
cout << "Ange ett nummber som du vill multiplicera: \n\n";
cin >> a;
cout << "\n";
cout << "Ange det andra nu: \n";
cin >> b;
cout << "\n";
if(a == 1)
{
multi(a,b);
cout << "Svaret är: " << x << "\n";
}
else if (a =! 1)
{
ans;
cout << "\n" << ab;
}
return 0;
}
Best regards.
a =! 1 is not what you think it is. It's an assignment that assigns !1 (which yields 0) to a, so that condition will never be true. The unequality operator is !=, but there you just want else, with no additional condition. Also, to call a function ans, you need to do ans():
if (a == 1) {
multi(a, b);
// ...
} else {
ans();
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With