java初级编程问题
其他问答
1
从键盘输入一个正整数n(如果输入数据不符合要求,提醒用户重新输入,直到满足要求为止),求解1-n之间所有奇数的和。请使用循环语句实现
-
import java.util.Scanner;
public class Calc { public static void main(String[] args){ int sum = 0; System.out.println("请输入一个整数n:"); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); for (int i=1;i<=n;i++){ //奇数 if(i % 2 != 0){ sum = sum + i; } } System.out.println(sum); } }
-
#include int main(int argc, char* argv[]) { int n = 0; for (;;) { printf("please intput a number!!\n"); char str1[5]; gets(str1); n = atoi(str1); if (n <= 0) { printf("input error!!\n"); continue; } break; } int total = 0; for (int i = 0; i <= n; ++i) { if (i % 2 == 0) { continue; } total += i; } printf("n = %d, total = %d\n", n, total); return 0; }
发表回复