Trying to sort out user input error in C - user-input

Hiya, I'm trying to make a small loop which presents an error when the user inputs something apart from a float and gives them another opportunity. Here's what I've got so far.
printf("Enter a value for x: ");
while (scanf("%lf", &x_temp) != 1) {
printf("ERROR: Input real number\n");
printf("Enter a value for x: ");
scanf("%lf", &x_temp);
}
But this just runs through the loop without giving the user another chance to enter another number:
user#user-vm:~/Desktop/Exercise_0$ ./a.out
Enter a value for x: a
ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Enter a value for x: ERROR: Input real number
Anyone got any ideas? Cheers guys

Try this:
for (;;)
{
printf("Enter a value for x: ");
if (scanf("%lf", &x_temp) == 1)
break;
printf("ERROR: Input real number\n");
}

You're not using the return value of the second scanf call anywhere. So it's probably succeeding, but then you immediately do another scanf at the top of the loop, after the input has already been consumed.

I'm not sure what the behavior is, but it appears you have an extra scanf(). The one that is part of the while condition will repeat each time through the loop. I don't see a need for the second one at the bottom of the loop.

Related

change style code function VScode time optimisation while coding

my goal is change a function to a format where the return value of the function is treated :
For example ; treating a the function scanf()
Return value of scanf : The value EOF is returned if the end of input is reached before
either the first successful conversion or a matching failure occurs.
EOF is also returned if a read error occurs, in which case the error
indicator for the stream (see ferror(3)) is set, and errno is set to
indicate the error.
Thus
scanf("%d\n",&i);
will be change to
#define RVAL(exp) do {if ((exp) == -1) { perror (#exp); exit(1); }} while (0)
...
RVAL(scanf("%d\n",&i));
Thus I want this to be done quickly means :
so what i do is look for occurences of "scanf" and replace it with "RVAL(scanf"
but the problem is i have to add another right parentheses
Can this be done fast ? using a techniques ? or a style ? where each whenever I enter scanf(); its replaced witch rval(scanf());
If you don't have many ) in your format string you can use a regex with (scanf([^)]*)); and replace with rval(\1);
*see comment

Try and Except statement - Automate The Boring Stuff {collatz() program}

I have been trying to complete a task from automate the boring stuff.
This is the task."Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.
Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.Add try and except statements to the previous project to detect whether the user types in a noninteger string."
def collatz(num):
ev_odd = num % 2 #detecs whether number is odd or even
if ev_odd == 1:
num = num * 3 + 1
else:
num = num//2
print(num)
global number
number = num
#the program
print('enter an integer')
number = int(input())
collatz(number)
while number != 1:
collatz(number)
i made this code it is working fine.But I am unable to use try and except statement to this..Help me out. Other recommendation to improve this code are requested.
Regards

How do take natural log of a double in MATLAB?

I am attempting to that the natural log of a number, I get the message:
tf2 = 60*ln(B1);
Undefined function 'ln' for input arguments of type 'double'.
So i try to cast the number as a float which the documentation claims it will accept but
then i get the error message :
float(B1);
Error using float (line 50)
The input argument to float was not a supported type. The only recognized strings are 'single' and 'double'. The input type was 'double'
So then i try to cast the double as a single and get the same error but it says :
f=single(B1);
float(B1);
Error using float (line 50)
The input argument to float was not a supported type. The only recognized strings are 'single' and 'double'. The input type was 'single'
The natural log in MATLAB is simply log(x). You're mixing the two:
log in MATLAB
log in MuPAD
The error message you get is because the function is not defined. You'll get the same error for this line:
bogus_function(1.23)
??? Undefined function or method 'bogus_function' for input arguments
of type 'double'.
I know it's an old question but as I didn't find a good answer when I was trying to do it so I will write my solution for others.
First there is no implemented function to do ln operation in matlab, but we can make it.
just remember that the change formula for log base is
log b (X)= log a (X)/log a (B)
you can check this easily.
if you want to calculate log 2 (8)
then what you need to do is to calculate log 10 (8)/log 10 (2)
you can find that: log 2 (8) = log 10 (8)/log 10 (2) = 3
So easily if you want to calculate ln(x), all you need is to change the base to the e.
ln(x) = log 10 (x)/log 10 (e)
so, just write that code in matlab
my_ln= log 10 ( number ) / log 10 ( exp(1) );
you can also make it as a function and call it whenever you need it,
function [val] = ln_fun(number)
val = log 10 (number)/ log 10 ( exp(1) );
end
*remember the log general formula → log base (number)

What is "index should be positive integer(not complex format integer)" in MATLAB?

// I made function like this:
function y = ZL(L,f)
if isvector(f)
y=1j*2*pi.*f*L;
else
y=1j*2*pi.*f*L;
end
// and command :
L = 10,
f= -10000:100:10000,
ZL=ZL(L,f);
// then error :
index should be positive integer(not complex format integer) or boolean
-> this error is translated by me who is Korean; sorry
what's wrong with it?
First time you call ZL = ZL(L,f), you don't get any error.
If you try to call your command a second time, you'll get this error: Index exceeds matrix dimensions. It's because you affect the variable ZL, so the second time it's not the function you're calling but you"re trying to get elements from the array ZL.
So please don't use same name for a variable and an existing function, otherwise the function name is masked by the variable.

matlab 'for' loop not executing last step or single step

I don't understand why the for cycle does not execute the last cycle, i.e. the field 'PX_TO_BOOK_RATIO'.
javaaddpath('C:\DocumentsandSettings\cascari\Desktop\API\APIv3\JavaAPI\v3.7.1.1\lib\blpapi3.jar')
connection = blp;
FileName='ScopeEconomies';
list={'OPM LN Equity';'FCTY US Equity';'FCCY US Equity'}
bbgfields={'TOT_LOAN_TO_TOT_ASSET'; 'PX_TO_BOOK_RATIO' };
nfields=length(bbgfields);
for i=1:nfields
[data,sec] = history(connection, list, bbgfields(i), '01/01/1993', '12/31/2013',...
{'quarterly','all_calendar_days','nil_value'},'USD');
temp=[data{:,:}];
eval([char(bbgfields(i)) '=temp']);
name=char(bbgfields(i));
xlswrite(FileName, temp, name, 'B1');
end;
When instead I leave only one element in bbgfields, I get
Attempted to access j(1); index out of bounds because numel(j)=0.
Error in blp/history>eventHandler (line 417)
outInd(i) = j(1);
Error in blp/history (line 245)
[d,sec] = eventHandler(b,s,f);
I am guessing it is because you are using a cell as an input into history. Have you tried converting it to char as follows?
[data,sec] = history(connection, list, char(bbgfields(i)), '01/01/1993', '12/31/2013',...
{'quarterly','all_calendar_days','nil_value'},'USD');