I was trying to make letters into numbers in c++. When I write in console it should count modulo and type out if ship is coming (i did all, but can't make letters into numbers :/ )
This what should happen: ABC a = 1; b=2; c=3 1*2*3=6....
So I need to write a word and it should be separated into letters and converted into numbers like that.
I am just learning and I don't know much :)
My current code:
int shipnum, groupnum, moduleship, modulegroup;
cout << "type ship number "; cin >> shipnum;
cout << "type group number "; cin >> groupnum;
/*shipnum dabar 5... (5 mod 2)
groupnum dabar 3... (3 mod 2)
*/
moduleship = shipnum % 47; //skaiciuojam moduli...
modulegroup = groupnum % 47;
if (moduleship == modulegroup) {
cout << "YES ship is coming for you :)";
}
else if (moduleship != modulegroup) { // "!=" reiskia "nelygu"
cout << "SORRY, NO ship for you :(";
}
return 0;
Your question isn't precise, although I find it enough. Tip: Be precise with the information you provide, there's no need to show the rest of the code.
Lets say we have this char Ship[20]="ABCDEF";. If you encoding is as simple as A=1, B=2, etc, then you only need something like this:
char Ship[20]="ABCDEF";
int decoded=1;
for(int i=1; Ship[i]=!'/0'; ++i) {
decoded = decoded * i
}
cout<<decoded;
This loop will run till it encounters the '\0' (null character) at the end of the string. So, you would have a factorial on the fact that your codeing (A=1,B=2, etc) represents a factorial.
otherwise, you could use a switch case, or if statements to check for individual characters and decode appropriately.
char Ship[20]="ABCDEF";
int decoded=1;
for(int i=1; Ship[i]=!'/0'; ++i) {
switch(Ship[i]){
case 'A' : decoded = decoded * 1;
break;
case 'B' : decoded = decoded *2;
break;
//So on
default : break;
}
}
cout<<decoded;
Output in both cases:
720
"convert letters into numbers (A=1; B=2…)"
string a{"ABC"};
int a0 = a[0]; // 65
int a1 = a[1]; // 66
int a2 = a[2]; // 67
.....
want to wrap A = 1, B = 2...
a0 = a0 - (65 - 1);
a1 = a1 - (65 - 1);
....
The question is not clear but i think the question basically is to convert char into int which follows the encoding A=1, B=2, ......, Z=26 and do the required processing which is to multiply all the encodings.
So here is how you could do it:
#include <iostream>
#include <string>
using namespace std;
int main(){
string s; //Input string
cout << "enter the string(CAPITALS ONLY) :";
cin >> s; //read the input string
int result = 1;
for (auto &elem : s){ //process all the characters of s
result *= elem - 'A' + 1; //corresponding int value is multiplied to the result
}
cout << "the result is :" << result;
}
Sample Output:
enter the string(CAPITALS ONLY) :AEF
the result is :30
(a+b)2=a2+b2+2ab: in cpp example
#include<iostream>
using namespace std;
//Declaring Function in scope
void firstFormula();
int main(void) //Main function
{
cout << "Hello World!!" << endl; //sample test text printing
firstFormula(); //executing function
return 0;
}
//function implementation
void firstFormula(){
//initializing variables
int a, b;
cout << "Enter Value of A" << endl;
cin >> a;//updating input values of a
cout << "Enter Value of B" << endl;
cin >> b;//updating input values of b
int v1 = a + b; //(a+b)2
int v2 = v1 * v1; //L.H.S
cout << "Value of v1=" << v1 << endl << "V2=" << v2 << endl;
cout << "Value of a=" << a << endl << "Value of B=" << b << endl;
int v3 = a * a;
int v4 = b * b;
int v5 = 2 * a * b;
int v6 = v3 + v4 + v5; //` R.H.S value after equation` `egfyufe`
cout << "Output=" << "V3=" << v3 << endl << "V4=" << v4 << endl << "v5="
<< v5 << endl << "V6=" << v6 << endl;
} //end
Related
when user input a character and press enters to take next input, output window asks to press any key and exit, please help me out to get remaining code working,
Here is the code
char r, R;
char c;
int channels;
int resedential()
{
// float channelscost = costperchannel*channels;
// float Bill = channelscost+processingfee+basiccost;
// cout << "Dear Customer Here is Your Bill" <<" "<<Bill<<endl;
}
int main()
{
cout << " Enter Customer Type" << " " << endl;
cin >> c;
if( c == r || R )
{
cout << " Enter Customer Type" << " " << endl;
cin >> c;
}
}
One thing I recognise, is that your if statement doesn't do what you think it does. Right now you aren't checking if c is equal to R.
Fixed Code:
if(c == r || c == R)
{
cout << "Enter Customer Type " << endl;
cin >> c;
}
Also check that there are actual values in r and R. So it doesn't compare to a constant (char(0)) – ASCII code NUL, resulting from default initialization of file-scoped variables to zero.
Example:
char r = 'A';
char R = 'B';
I would like to read numbers into a static array of fixed size 10, but the user can break the loop by entering character E.
Here's my code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
cin >> myArray[i];
if (myArray[i] != 'E')
{
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
cout << count << endl;
system("PAUSE");
return 0;
}
However, I get the following results while entering E:
Enter upto 10 integers. Enter E to end
Enter num 1:5
5
Enter num 2:45
45
Enter num 3:25
25
Enter num 4:2
2
Enter num 5:E
-858993460
Enter num 6:-858993460
Enter num 7:-858993460
Enter num 8:-858993460
Enter num 9:-858993460
Enter num 10:-858993460
10
Press any key to continue . . .
How can I fix this code in the simplest way?
cin fails for parsing character 'E' to int. The solution would be to read string from user check if it is not "E" (it is a string not a single char so you need to use double quotes) and then try to convert string to int. However, this conversion can throw exception (see below).
Easiest solution:
#include <iostream>
#include <cmath>
#include <string> //for std::stoi function
using namespace std;
int main()
{
int myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
std::string input;
cin >> input;
if (input != "E")
{
try
{
// convert string to int this can throw see link below
myArray[i] = std::stoi(input);
}
catch (const std::exception& e)
{
std::cout << "This is not int" << std::endl;
}
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
cout << count << endl;
system("PAUSE");
return 0;
}
See documentation for std::stoi. It can throw exception so your program will end suddenly (by termination) that is why there is try and catch blocks around it. You will need to handle the case when user puts some garbage values in your string.
Just use:
char myArray[10];
because at the time of taking input console when get character then try to convert char to int which is not possible and store default value in std::cin i.e. 'E' to 0 (default value of int).
Use below code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char myArray[10];
int count = 0;
cout << "Enter upto 10 integers. Enter E to end" << endl;
for (int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
cin >> myArray[i];
if (myArray[i] == 'E')
{
break;
}
else
{
cout << myArray[i] << endl;
count++;
}
}
exitloop:
cout << count << endl;
system("PAUSE");
return 0;
}
Output:
Enter upto 10 integers. Enter E to end
Enter num 1:1
1
Enter num 2:E
1
sh: 1: PAUSE: not found
If you debug this, you will find all your myArray[i] are -858993460 (=0x CCCC CCCC), which is a value for the uninitialized variables in the stack.
When you put a E to an int variable myArray[i]. std::cin will set the state flag badbit to 1.
Then when you run cin >> myArray[i], it will skip it. In other words, do nothing.
Finally, you will get the result as above.
The problem is that attempting to read E as an int fails, and puts the stream in an error state where it stops reading (which you don't notice because it just doesn't do anything after that) and leaves your array elements uninitialized.
The simplest possible way is to break on any failure to read an integer:
for(int i = 0; i < 10; i++)
{
cout << "Enter num " << i + 1 << ":";
if (cin >> myArray[i])
{
cout << myArray[i] << endl;
count++;
}
else
{
break;
}
}
If you want to check for E specifically, you need to read a string first, and then convert that to an int if it's not E.
As a bonus, you need to handle everything that's neither int nor E, which complicates the code a bit.
Something like this:
int count = 0;
string input;
while (cin >> input && count < 10)
{
if (input == "E")
{
break;
}
istringstream is(input);
if (is >> myArray[count])
{
cout << myArray[count] << endl;
count++;
}
else
{
cout << "Please input an integer, or E to exit." << endl;
}
}
I am writing a program that takes in 3 user inputted values for a quadratic equation, does some calculation, and returns how many roots the quadratic has.
When I print *(point), it gives me the correct value from the function.
However, when I use *(point) in the If conditions, it does not seem to work the way I want it to - I believe that *(point)is always some positive number, hence why it always executing that specific if condition.
The user values: a = 9, b = -12, c = 4 should print out This quadratic has 1 root. and the values: a = 2, b = 16, c = 33 should print out This quadratic has 2 roots. BUT the program always prints out This quadratic has 0 roots. no matter what the values entered.
Here is my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
float *quadratic(float a1[]);
int main()
{
float a1[3] = {};
float *point;
cout << "Enter a: ";
cin >> a1[0];
cout << "\nEnter b: ";
cin >> a1[1];
cout << "\nEnter c: ";
cin >> a1[2];
point = quadratic(a1);
cout << endl << "d = " << *(point) << endl;
if (*(point) < 0) {
cout << "\nThis quadratic has 2 roots.\n";
}
else if (*(point) > 0) {
cout << "\nThis quadratic has 0 roots.\n";
}
else { //else if *(point) is equal to 0
cout << "\nThis quadratic has 1 root.\n";
}
return 0;
}
float *quadratic(float a1[]) {
float d;
d = (a1[1] * a1[1]) - (4 * a1[0] * a1[2]);
float xyz[1] = { d };
return xyz;
}
Your function quadratic returns a pointer to a local array. After the function return that array doesn't exist anymore. The pointer is then a dangling pointer, a pointer pointing to a place in memory that has once held an object, but that now may hold anything or just rubbish.
Since the array that quadratic attempts to return is always one value there is no need for returning an array. Just return that value.
You don't even need to deal with arrays for the polynomial's coefficients, since they're always three, but if array seems better than individual a, b and c variables, then just use std::array, e.g. like this:
#include <iostream>
#include <array>
#include <vector>
using namespace std;
using Float = double;
auto square_of( Float const v ) -> Float { return v*v; }
auto determinant( array<Float, 3> const& a )
-> Float
{
return square_of( a[1] ) - 4*a[0]*a[2];
}
auto main()
-> int
{
array<Float, 3> a;
cout << "Enter A: "; cin >> a[0];
cout << "Enter B: "; cin >> a[1];
cout << "Enter C: "; cin >> a[2];
Float const d = determinant( a );
cout << "d = " << d << endl;
if( d < 0 )
{
cout << "This quadratic has 2 roots." << endl;
}
else if( d > 0 )
{
cout << "This quadratic has 0 roots." << endl;
}
else // d == 0
{
cout << "This quadratic has 1 root.";
}
}
The code above is equivalent to what I perceived as the intent of your code.
However, I'd check out the formula for roots of quadratic equations, and test the program, before handing in something.
I have created a program which takes an equation. from the user by asking about the degree of the equation. and then taking the co-efficients from the user and then forming the function which results into an equation. and then I have used the bisection method to solve it.
The program is::
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
int stop=0,d,t[]={1};
float f(float x)
{
int loop,loopa;
float add=0.0,sum=0.0;
for(;stop==0;)
{
int p ;
cout << "Enter the degree of the poly. eq. (+ve integer)" << endl;
cin >> d ;
int *t = new int[d+1];
cout << "The eq. will be in the form of ax^"<<d<<"+bx^"<<(d-1)<<" and so on ." ;
p = 97 + d ;
for(loop=d;loop>=0;loop--)
{
cout << "Enter the value of " << char(p-loop) << endl;
cin >> t[loop];
cout << "a="<<t[loop]<<endl;
}
stop=1; //ARRAY IS STILL THERE WHY/////
} for(loop=0;loop<=d;loop++) cout<<"out="<<t[loop]<<endl;
//ARRAY IS GONE TILL NOW//
cout<<"d="<<d<<endl;
for(loopa=d;loopa>=0;loopa--)
{
cout<<"loopa="<<loopa<<"value="<<t[loopa]<<endl;
add = t[loopa] * pow(x,loopa);
sum=sum+add;
}
return sum;
}
int main()
{
float a , b , c , i , j ;
A:
cout << " Enter the starting point of interval " <<endl;
cin >> a ;
cout << " Enter the end point of interval " << endl;
cin >> b ;
cout << " Enter the number of iterations to be done . ( More the iterations , accurate is the result ) " << endl;
cin >> i ;
for(j=0;j<i;j++)
{
if(f(a)*f(b)>0)
{
cout << " The root of the above polynomial does not lies in the given interval . TRY AGAIN " << endl;
goto A;
}
else
{
c = a + b ;
c = c / 2 ;
if (f(a)*f(c)>0) a = c ;
else b = c ;
cout <<"hello"<< a << "aa \t" << b << "\t" << c << endl;
}
}
cout << "Root = "<< c <<endl;
}
When the user gives the value of degree it creates an array of size one more than degree is created then there is a for loop which takes the value of co-efficients in that array . The problem is the value of the array stays intact till the first for loop . but as the control proceeds to the second loop ( see the two comments ) the value of the array is gone...I am using CodeLite ...guys help me?????
To solve the array issue you just need to make a few small changes.
int stop=0,d,*t; // Declare an uninitialized pointer to int
float f(float x)
{
int loop,loopa;
float add=0.0,sum=0.0;
for(;stop==0;)
{
int p ;
cout << "Enter the degree of the poly. eq. (+ve integer)" << endl;
cin >> d ;
t = new int[d+1]; // Remove the int and asterix before t. You want to assign the new array to the pointer, not the value the pointer is pointing to.
cout << "The eq. will be in the form of ax^"<<d<<"+bx^"<<(d-1)<<" and so on ." ;
p = 97 + d ;
for(loop=d;loop>=0;loop--)
{
cout << "Enter the value of " << char(p-loop) << endl;
cin >> t[loop];
cout << "a="<<t[loop]<<endl;
}
stop=1; //ARRAY IS STILL THERE WHY/////
} for(loop=0;loop<=d;loop++) cout<<"out="<<t[loop]<<endl;
//ARRAY IS GONE TILL NOW//
cout<<"d="<<d<<endl;
for(loopa=d;loopa>=0;loopa--)
{
cout<<"loopa="<<loopa<<"value="<<t[loopa]<<endl;
add = t[loopa] * pow(x,loopa);
sum=sum+add;
}
delete[] t; // All new'ed things need to be deleted to not cause a leak. Delete it here since it is no longer needed.
return sum;
}
Please note that even if this works, it is not advised to use raw pointers in C++. Better to use an std::array<int> or std::vector<int> so you don't have to take care of the allocating and deleting of memory.
EDIT: Accidentaly left the int in fron of t. Changed now.
I wanted to take an input char and then from that get a predefined number which was assigned to the char.
Example
int A=100;
char in;
cin>>in; //input A;
and then use that in char to identify with A and pass the value it holds.
sorry if i am not that clear.
As mentioned in a comment on your question, you'd want to use a map
#include <map>
...
std::map<char, int> char_map = {
{'A', 100}
};
char in;
std::cin >> in; //input A;
std::cout << char_map[in] << std::endl;
Of course you would probably need to add some form of verification on the key.
Simple example
#include <iostream>
#include <unordered_map>
int main(void)
{
char c;
std::unordered_map<char, int> uMap;
for (int i = 'A'; i <= 'Z'; i++)
{
uMap[i] = i - 'A' + 1;
}
c = fgetc(stdin);
std::cout << "\nCharacter '" << c << "' has value " << uMap[c];
return 0;
}
Input
1. A
2. C
3. Z
Output
1. Character 'A' has value 100
2. Character 'C' has value 102
3. Character 'Z' has value 125
your input is a char so you can compare it against some other chars too
char input;
std::cin >> input; //input A;
std::cout << "input: " << input << std::endl;
if (input == 'A')
{
std::cout << "input was A: " << std::endl;
}
else
{
std::cout << "input was not: " << std::endl;
}