def hex_numb(a): # to print or create a string of hex numbers frm 0-F
for a in range (a,16):
b=hex(a)
b=b[2]
b=b.upper()
a+=1
print b
Returns 0-F all 16 digits and None after F
A couple of comments:
Why is there an argument (a) to this function? If you always want 0-F, remove the argument, and if you want to specify the value to be returned lose the for loop.
When using a for x in range(n) loop, you don't need to manually increment x (i.e. x += 1) inside the loop.
Your various string manipulations can be done in one go: b = hex(a)[2].upper().
Your function is returning None implicitly (standard Python behaviour when your function doesn't explicitly return), so if you print hex_numb(0) you run the function, printing all the values, then print the return value, None. All of the printing work is done inside the function, just call it: hex_numb(0).
Related
I represents the global variable i.e the name I represents same variable inside and outside the function. Fact is first called when I = 1, which is the first value written. This value is
passed to the function's dummy argument N. The same I is now given the initial value 2 by the DO loop inside Fact, but since it is greater than N, the DO loop is not executed, so I still has the value 2
when Fact returns to be printed in the main program. However, I is now incremented to 3 in the
DO loop in the main program, which is the value it has when the second call to Fact takes place.
PROGRAM Factorial
IMPLICIT NONE
INTEGER I
DO I = 1, 10
PRINT*, I, Fact(I)
END DO
CONTAINS
FUNCTION Fact( N )
INTEGER Fact, N, Temp
Temp = 1
DO I = 2, N
Temp = I * Temp
END DO
Fact = Temp
END FUNCTION
END
and Once it completes I goes from 2 to N where now N =3..Now the function must returns I =3 to main program such that next I should be 4 in Do loop of main program, but when compiled and run..it only shows factor for 3,5,7 and 9.....My question is why it skip 4 or 6 or 8.
After exiting a loop the control variable gets the value of the upper bound + 1. However, it is illegal to modify the value of a loop control variable and anything can happen if you manage to do that despite the compiler's checks. It is an undefined behaviour then.
Not only that, you are aliasing the global I by using it as I as N at the same time inside the function. The compiler can probably perform various optimizations assuming that they are distinct when in fact they refer to the same variable. The program is therefore again illegal and unpredictable.
Consider this example and try to compile it with different optimization levels. You will get different answers:
i = 1
call s(i)
contains
subroutine s(j)
do k = 1, 10
j = i + j
end do
print *, j
end
end
Try it online!
This particular problem can probably be fixed by declaring i or the dummy argument target.
This question already has an answer here:
Function in fortran, passing array in, receiving array out
(1 answer)
Closed 4 years ago.
INTEGER FUNCTION NUMTOLIST(NUM) RESULT(LI)
IMPLICIT NONE
! FUNCTION TO CONVERT NUMBERS INTO ARRAYS OF NUMBERS, BY DIGIT
! PROBLEM 1: X IS NOT BEING PASSED
INTEGER :: NUM
INTEGER :: I,J
INTEGER :: LI(0:5) ! G95 COMPILER SAYS THAT 'LI ALREADY HAS BASIC TYPE INTEGER', DOESN'T RECOGNISE AS ARRAY
PRINT *,'NUM: ',NUM ! DEBUGGING LINE, CONFIRMS THAT X IS NOT BEING PASSED INTO THE FUNCTION
DO I = 0,5
J = 0
DO WHILE (J*10**(5-I)<=NUM)
J = J+1
END DO
J = J-1
LI(I) = J
NUM = NUM-(J*10**(5-I))
END DO
PRINT *,'LI: ',LI ! DEBUGGING LINE, SHOWS THAT FUNCTION IS AS IS SUPPOSED TO, EXCEPT FOR ON SOME SORT OF DEFAULT INTEGER
RETURN
END FUNCTION NUMTOLIST
PROGRAM NUMTOLISTTEST
IMPLICIT NONE
INTEGER FUNCTION, NUMTOLIST
INTEGER :: X
INTEGER :: F(1:6)
READ *,X
PRINT *,X
F = NUMTOLIST(X)
! PROBLEM 2: THE RESULT OF NUMTOLIST SHOULD BE A LIST, BUT F IS JUST BEING ASSIGNED NUM, NOT THE OUTPUT OF NUMTOLIST
PRINT *,F
READ *,X
END PROGRAM NUMTOLISTTEST
Here is my full code. As the name suggests, this is a test for a function of a larger code. There are several problems but the one that is most pressing is that for some reason a variable is not being passed to a function. I am using the silverfrost compiler, and for some reason although everything in the function itself is working as it should, it neither inputs nor returns properly. The input itself is completely disregarded, leading to num being undefined, and the return isn't being read as a list type, as F, when printed, is a list of the arbitrary number num took on. It's completely beyond me why any of this is happening, and I've been on and off looking at this for a couple of days.
Much more trivially, when I try to compile using G95, it won't. It claims that 'Li already has basic type 'Integer'', and then won't recognise Li as a list. The method I'm using to declare an integer as a list has worked in the past for me, and fits the documentation I've seen, so I'm confused why it's throwing an error.
I've been stuck on this for a while, and I just can't seem to fix it on my own. Whatever help is offered will be greatly appreciated, and thank you in advance.
You are indeed declaring a type for the variable LI twice in the function. Look:
INTEGER FUNCTION NUMTOLIST(NUM) RESULT(LI)
! (...)
INTEGER :: LI(0:5)
Notice the INTEGER keyword before function declaration. It applies to the variable name declared as result in result(LI). The second declaration of LI gives the error.
Solutions:
Remove the INTEGER from the function declaration (preferred);
Remove the second type declaration of LI. You can specify a dimension without type declaration, with the dimension specification statement.
like this:
DIMENSION LI(0:5)
Besides that, to call a function with an array as a returning value, you will need an explicit interface.
I want to assign a value of 097 to an integer variable. I don't want it to get implicitly converted to 97. Is this possible?
int i=097;
cout<<i;
OUTPUT as 097 : Possible?
I need to put the value in the link list in reverse order. So if the user is inputting 097 I need to parse it digit wise and store in link list as 7->9->0. Its not the exact program but its something I am trying to achieve. There can be other ways like using arrays and all. But I was just wondering if I can parse 0 via using int variable.
No, this is not possible.
Integers are stored in binary, not as individual digits. Therefore, all information not related to the value of the integer is not stored.
Perhaps you would like to store your value in a string instead?
It doesn't make sense to say that the value of an int is 97 or 097. What you want is a way to format your output. To do that, can std::setwidth and std::setfill.
cout << setwidth(3) << setfill('0') << i;
Not with an integer variable. To achieve this, you could either use a string or some other method of tracking how many leading zeros the number should have.
Incidentally, a leading zero in a C++ integer literal turns it into an octal literal. This makes your program malformed since it's trying to use a non-octal digit 9 in an octal literal.
As others have suggested, try using a string to display the value.Use to_string function to convert the integer to a string and just insert a leading zero at the beginning.
int i = 97;
std::string s = std::to_string(i);
s.insert(0,"0");
EDIT: You can then store the digits into the list by iterating through the string.
i have following part of code:
string v;
getline(linestream,v,' ');
double d=atof(v.c_str());
fprintf(writeFile3,"%f\n",(double)d);
but lets say first line has value 0.08012901 but d=0.080129 last 2 values are omitted, how can i get full double value?
Thank you
If you want the digits copied exactly, by far the easiest way to go is to just leave the digits in string form:
string v;
getline(instream, v, ' ');
outstream << v;
Almost anything that converts the digits to a double, then prints out the value has at least some chance of producing a result that's slightly different from the input.
It's not that the decimal places are not stored in the d. It's just that fprintf only prints 6 decimal places by default. To print 8, try
fprintf(writeFile3, "%.8f\n", d);
You don't have to cast d as a double since it already is of type double.
I would add to the answer above that whatever you put after the variable call is what you will display. By default C++ will show 6.
ie
fprintf(writeFile3, "%.3f\n", (double)d); will display 3 decimal points at the end. It will also pad so if there is possible for longer than 8 decimal places you will want to make it more than that. That I know of you cannot set a flag to just display all decimal points. It has to be explicit.
If there are non-number characters in a string and you call atoi [I'm assuming wtoi will do the same]. How will atoi treat the string?
Lets say for an example I have the following strings:
"20234543"
"232B"
"B"
I'm sure that 1 will return the integer 20234543. What I'm curious is if 2 will return "232." [Thats what I need to solve my problem]. Also 3 should not return a value. Are these beliefs false? Also... if 2 does act as I believe, how does it handle the e character at the end of the string? [Thats typically used in exponential notation]
You can test this sort of thing yourself. I copied the code from the Cplusplus reference site. It looks like your intuition about the first two examples are correct, but the third example returns '0'. 'E' and 'e' are treated just like 'B' is in the second example also.
So the rules are
On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.
According to the standard, "The functions atof, atoi, atol, and atoll need not affect the value of the integer expression errno on an error. If the value of the result cannot be represented, the behavior is undefined." (7.20.1, Numeric conversion functions in C99).
So, technically, anything could happen. Even for the first case, since INT_MAX is guaranteed to be at least 32767, and since 20234543 is greater than that, it could fail as well.
For better error checking, use strtol:
const char *s = "232B";
char *eptr;
long value = strtol(s, &eptr, 10); /* 10 is the base */
/* now, value is 232, eptr points to "B" */
s = "20234543";
value = strtol(s, &eptr, 10);
s = "123456789012345";
value = strtol(s, &eptr, 10);
/* If there was no overflow, value will contain 123456789012345,
otherwise, value will contain LONG_MAX and errno will be ERANGE */
If you need to parse numbers with "e" in them (exponential notation), then you should use strtod. Of course, such numbers are floating-point, and strtod returns double. If you want to make an integer out of it, you can do a conversion after checking for the correct range.
atoi reads digits from the buffer until it can't any more. It stops when it encounters any character that isn't a digit, except whitespace (which it skips) or a '+' or a '-' before it has seen any digits (which it uses to select the appropriate sign for the result). It returns 0 if it saw no digits.
So to answer your specific questions: 1 returns 20234543. 2 returns 232. 3 returns 0. The character 'e' is not whitespace, a digit, '+' or '-' so atoi stops and returns if it encounters that character.
See also here.
If atoi encounters a non-number character, it returns the number formed up until that point.
I tried using atoi() in a project, but it wouldn't work if there were any non-digit characters in the mix and they came before the digit characters - it'll return zero. It seems to not mind if they come after the digits, for whatever reason.
Here's a pretty bare bones string to int converter I wrote up that doesn't seem to have that problem (bare bones in that it doesn't work with negative numbers and it doesn't incorporate any error handling, but it might be helpful in specific instances). Hopefully it might be helpful.
int stringToInt(std::string newIntString)
{
unsigned int dataElement = 0;
unsigned int i = 0;
while ( i < newIntString.length())
{
if (newIntString[i]>=48 && newIntString[i]<=57)
{
dataElement += static_cast<unsigned int>(newIntString[i]-'0')*(pow(10,newIntString.length()-(i+1)));
}
i++;
}
return dataElement;
}
I blamed myself up to this atoi-function behaviour when I was learning-approached coding program with function calculating integer factorial result given input parameter by launching command line parameter.
atoi-function returns 0 if value is something else than numeral value and "3asdf" returns 3. C -language handles command line input parameters in char -array pointer variable as we all already know.
I was told that down at the book "Linux Hater's Handbook" there's some discussion appealing for computer geeks doesn't really like atoi-function, it's kind of foolish in reason that there's no way to check validity of given input type.
Some guy asked me why I don't brother to use strtol -function located on stdlib.h -library and he gave me an example attached to my factorial-calculating recursive method but I don't care about factorial result is bigger than integer primary type value -range, out of ranged (too large base number). It will result in negative values in my program.
I solved my problem with atoi-function first checking if given user's input parameter is truly numerical value and if that matches, after then I calculate the factorial value.
Using isdigit() -function located on chtype.h -library is following:
int checkInput(char *str[]) {
for (int x = 0; x < strlen(*str); ++x)
{
if (!isdigit(*str[x])) return 1;
}
return 0;
}
My forum-pal down in other Linux programming forum told me that if I would use strtol I could handle the situations with out of ranged values or even parse signed int to unsigned long -type meaning -0 and other negative values are not accepted.
It's important upper on my code check if charachter is not numerical value. Negotation way to check this one the function returns failed results when first numerical value comes next to check in string. (or char array in C)
Writing simple code and looking to see what it does is magical and illuminating.
On point #3, it won't return "nothing." It can't. It'll return something, but that something won't be useful to you.
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.