Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string isn't written out in function when called in if-statement. [closed]

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.

like image 454
LoneDruidOfTheDarkArts Avatar asked Jun 12 '26 13:06

LoneDruidOfTheDarkArts


1 Answers

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();
    // ...
}
like image 131
Cat Plus Plus Avatar answered Jun 15 '26 02:06

Cat Plus Plus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!